diff --git a/api/accounts/changepassword.go b/api/accounts/changepassword.go index 8066dae78d..83719cc70c 100644 --- a/api/accounts/changepassword.go +++ b/api/accounts/changepassword.go @@ -35,7 +35,7 @@ func (c *Client) ChangePassword(ctx context.Context, accountId, currentPassword, version = existingTarget.Item.Version } - reqBody := map[string]interface{}{ + reqBody := map[string]any{ "version": version, "current_password": currentPassword, "new_password": newPassword, diff --git a/api/accounts/setpassword.go b/api/accounts/setpassword.go index f12a61f668..b99e0de0f1 100644 --- a/api/accounts/setpassword.go +++ b/api/accounts/setpassword.go @@ -35,7 +35,7 @@ func (c *Client) SetPassword(ctx context.Context, accountId, password string, ve version = existingTarget.Item.Version } - reqBody := map[string]interface{}{ + reqBody := map[string]any{ "version": version, "password": password, } diff --git a/api/authmethods/authenticate.go b/api/authmethods/authenticate.go index e765551317..a2446e45b9 100644 --- a/api/authmethods/authenticate.go +++ b/api/authmethods/authenticate.go @@ -9,8 +9,8 @@ import ( ) type AuthenticateResult struct { - Command string `json:"-"` - Attributes map[string]interface{} `json:"-"` + Command string `json:"-"` + Attributes map[string]any `json:"-"` attributesRaw json.RawMessage response *api.Response @@ -20,7 +20,7 @@ func (a *AuthenticateResult) MarshalJSON() ([]byte, error) { // Note that a will not be nil per contract of the interface. Using a map // here causes Go to sort the resulting JSON, which makes tests easier and // output more predictable. - out := make(map[string]interface{}) + out := make(map[string]any) if a.Command != "" { out["command"] = a.Command } @@ -41,7 +41,7 @@ func (a *AuthenticateResult) UnmarshalJSON(inBytes []byte) error { } a.Command = i.Command a.attributesRaw = i.Attributes - a.Attributes = make(map[string]interface{}) + a.Attributes = make(map[string]any) if err := json.Unmarshal(i.Attributes, &a.Attributes); err != nil { return err } @@ -57,7 +57,7 @@ func (n AuthenticateResult) GetResponse() *api.Response { } // Authenticate is a generic authenticate API call that returns a generic result. -func (c *Client) Authenticate(ctx context.Context, authMethodId, command string, attributes map[string]interface{}, opt ...Option) (*AuthenticateResult, error) { +func (c *Client) Authenticate(ctx context.Context, authMethodId, command string, attributes map[string]any, opt ...Option) (*AuthenticateResult, error) { if c.client == nil { return nil, fmt.Errorf("nil client in Authenticate request") } @@ -70,7 +70,7 @@ func (c *Client) Authenticate(ctx context.Context, authMethodId, command string, _, apiOpts := getOpts(opt...) - reqBody := map[string]interface{}{ + reqBody := map[string]any{ "command": command, } if attributes != nil { diff --git a/api/authmethods/authenticate_test.go b/api/authmethods/authenticate_test.go index 932a5fa742..dc06077b75 100644 --- a/api/authmethods/authenticate_test.go +++ b/api/authmethods/authenticate_test.go @@ -14,7 +14,7 @@ func TestAuthenticateResultMarshaling(t *testing.T) { exp := &AuthenticateResult{ Command: "foo", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "key": "value", }, attributesRaw: json.RawMessage(`{"key":"value"}`), diff --git a/api/authmethods/changestate.go b/api/authmethods/changestate.go index d631b2c28a..01377802dc 100644 --- a/api/authmethods/changestate.go +++ b/api/authmethods/changestate.go @@ -46,9 +46,9 @@ func (c *Client) ChangeState(ctx context.Context, authMethodId string, version u reqBody := opts.postMap reqBody[versionPostBodyKey] = version - attrMap, ok := reqBody[attributesPostBodyKey].(map[string]interface{}) + attrMap, ok := reqBody[attributesPostBodyKey].(map[string]any) if !ok { - attrMap = make(map[string]interface{}) + attrMap = make(map[string]any) reqBody[attributesPostBodyKey] = attrMap } attrMap[statePostBodyKey] = state diff --git a/api/client.go b/api/client.go index 9e9a848e38..97f1e86cce 100644 --- a/api/client.go +++ b/api/client.go @@ -594,7 +594,7 @@ func copyHeaders(in http.Header) http.Header { // NewRequest creates a new raw request object to query the Boundary controller // configured for this client. This is an advanced method and generally // doesn't need to be called externally. -func (c *Client) NewRequest(ctx context.Context, method, requestPath string, body interface{}, opt ...Option) (*retryablehttp.Request, error) { +func (c *Client) NewRequest(ctx context.Context, method, requestPath string, body any, opt ...Option) (*retryablehttp.Request, error) { if c == nil { return nil, fmt.Errorf("client is nil") } @@ -602,7 +602,7 @@ func (c *Client) NewRequest(ctx context.Context, method, requestPath string, bod // Figure out what to do with the body. If it's already a reader it might // be marshaled or raw bytes in a reader, so pass it through. Otherwise // attempt JSON encoding and then pop in a bytes.Buffer. - var rawBody interface{} + var rawBody any if body != nil { switch t := body.(type) { case io.ReadCloser, io.Reader: diff --git a/api/response.go b/api/response.go index 43be56709a..36df98bd4e 100644 --- a/api/response.go +++ b/api/response.go @@ -14,7 +14,7 @@ type Response struct { resp *http.Response Body *bytes.Buffer - Map map[string]interface{} + Map map[string]any } // HttpResponse returns the underlying HTTP response @@ -27,7 +27,7 @@ func (r *Response) StatusCode() int { return r.resp.StatusCode } -func (r *Response) Decode(inStruct interface{}) (*Error, error) { +func (r *Response) Decode(inStruct any) (*Error, error) { if r == nil || r.resp == nil { return nil, fmt.Errorf("nil response, cannot decode") } @@ -57,7 +57,7 @@ func (r *Response) Decode(inStruct interface{}) (*Error, error) { reader := bytes.NewReader(r.Body.Bytes()) dec := json.NewDecoder(reader) dec.UseNumber() - r.Map = make(map[string]interface{}) + r.Map = make(map[string]any) if err := dec.Decode(&r.Map); err != nil { return nil, fmt.Errorf("error decoding response to map: %w; response was %s", err, r.Body.String()) } diff --git a/api/targets/custom.go b/api/targets/custom.go index e6ee01fe95..976b392d6b 100644 --- a/api/targets/custom.go +++ b/api/targets/custom.go @@ -13,7 +13,7 @@ type SessionAuthorizationResult struct { response *api.Response } -func (n SessionAuthorizationResult) GetItem() interface{} { +func (n SessionAuthorizationResult) GetItem() any { return n.Item } diff --git a/internal/auth/additional_verification_test.go b/internal/auth/additional_verification_test.go index c871b71d12..5b9d3673aa 100644 --- a/internal/auth/additional_verification_test.go +++ b/internal/auth/additional_verification_test.go @@ -159,7 +159,7 @@ func TestRecursiveListingDifferentOutputFields(t *testing.T) { require.NotNil(resp) require.NotNil(resp.GetItems()) assert.Len(resp.GetItems(), 3) - items := resp.GetResponse().Map["items"].([]interface{}) + items := resp.GetResponse().Map["items"].([]any) require.NotNil(items) // The default generated roles don't have output field definitions for them, @@ -171,7 +171,7 @@ func TestRecursiveListingDifferentOutputFields(t *testing.T) { // auto generated one. var globalAms, orgAms int for _, item := range items { - m := item.(map[string]interface{}) + m := item.(map[string]any) require.NotNil(m) switch m["scope_id"].(string) { case scope.Global.String(): @@ -200,7 +200,7 @@ func TestRecursiveListingDifferentOutputFields(t *testing.T) { require.NotNil(resp) require.NotNil(resp.GetItems()) assert.Len(resp.GetItems(), 1) - item := resp.GetResponse().Map["items"].([]interface{})[0].(map[string]interface{}) + item := resp.GetResponse().Map["items"].([]any)[0].(map[string]any) assert.NotContains(item, "created_time") assert.NotContains(item, "attributes") } diff --git a/internal/auth/db_test.go b/internal/auth/db_test.go index 38306bbbfd..3338b2dbed 100644 --- a/internal/auth/db_test.go +++ b/internal/auth/db_test.go @@ -56,7 +56,7 @@ select count(*) from test_auth_method where public_id = @public_id org, _ := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper)) id := "l1Ocw0TpHn800CekIxIXlmQqRDgFDfYl" - inserted, err := rw.Exec(ctx, insert, []interface{}{sql.Named("public_id", id), sql.Named("scoped_id", org.GetPublicId())}) + inserted, err := rw.Exec(ctx, insert, []any{sql.Named("public_id", id), sql.Named("scoped_id", org.GetPublicId())}) require.NoError(err) require.Equal(1, inserted) @@ -64,7 +64,7 @@ select count(*) from test_auth_method where public_id = @public_id Count int } var count c - rows, err := rw.Query(ctx, baseTableQuery, []interface{}{sql.Named("public_id", id)}) + rows, err := rw.Query(ctx, baseTableQuery, []any{sql.Named("public_id", id)}) require.NoError(err) defer rows.Close() for rows.Next() { @@ -74,7 +74,7 @@ select count(*) from test_auth_method where public_id = @public_id assert.Equal(1, count.Count) count.Count = 0 - rows, err = rw.Query(ctx, testTableQuery, []interface{}{sql.Named("public_id", id)}) + rows, err = rw.Query(ctx, testTableQuery, []any{sql.Named("public_id", id)}) require.NoError(err) defer rows.Close() for rows.Next() { @@ -135,18 +135,18 @@ values org, _ := iam.TestScopes(t, repo) meth_id := "31Ocw0TpHn800CekIxIXlmQqRDgFDfYl" - _, err = rw.Exec(ctx, insertAuthMethod, []interface{}{meth_id, org.GetPublicId()}) + _, err = rw.Exec(ctx, insertAuthMethod, []any{meth_id, org.GetPublicId()}) require.NoError(err) id := "l1Ocw0TpHn800CekIxIXlmQqRDgFDfYl" - _, err = rw.Exec(ctx, insert, []interface{}{id, meth_id}) + _, err = rw.Exec(ctx, insert, []any{id, meth_id}) require.NoError(err) type c struct { Count int } var count c - rows, err := rw.Query(ctx, baseTableQuery, []interface{}{id}) + rows, err := rw.Query(ctx, baseTableQuery, []any{id}) require.NoError(err) defer rows.Close() for rows.Next() { @@ -156,7 +156,7 @@ values assert.Equal(1, count.Count) count.Count = 0 - rows, err = rw.Query(ctx, testTableQuery, []interface{}{id}) + rows, err = rw.Query(ctx, testTableQuery, []any{id}) require.NoError(err) defer rows.Close() for rows.Next() { diff --git a/internal/auth/oidc/account_claim_map_test.go b/internal/auth/oidc/account_claim_map_test.go index ac9c1f3c7e..e9729a5117 100644 --- a/internal/auth/oidc/account_claim_map_test.go +++ b/internal/auth/oidc/account_claim_map_test.go @@ -127,7 +127,7 @@ func TestAccountClaimMap_Create(t *testing.T) { assert.NoError(err) } found := AllocAccountClaimMap() - require.NoError(rw.LookupWhere(ctx, &found, "oidc_method_id = ? and to_claim = ?", []interface{}{tt.args.authMethodId, tt.args.to})) + require.NoError(rw.LookupWhere(ctx, &found, "oidc_method_id = ? and to_claim = ?", []any{tt.args.authMethodId, tt.args.to})) assert.Equal(got, &found) } }) @@ -208,7 +208,7 @@ func TestAccountClaimMap_Delete(t *testing.T) { } assert.Equal(tt.wantRowsDeleted, deletedRows) found := AllocAccountClaimMap() - err = rw.LookupWhere(ctx, &found, "oidc_method_id = ? and to_claim = ?", []interface{}{tt.AccountClaimMap.OidcMethodId, tt.AccountClaimMap.ToClaim}) + err = rw.LookupWhere(ctx, &found, "oidc_method_id = ? and to_claim = ?", []any{tt.AccountClaimMap.OidcMethodId, tt.AccountClaimMap.ToClaim}) assert.True(errors.IsNotFoundError(err)) }) } diff --git a/internal/auth/oidc/aud_claim_test.go b/internal/auth/oidc/aud_claim_test.go index 5589e98293..b2142b9e0d 100644 --- a/internal/auth/oidc/aud_claim_test.go +++ b/internal/auth/oidc/aud_claim_test.go @@ -113,7 +113,7 @@ func TestAudClaim_Create(t *testing.T) { assert.NoError(err) } found := AllocAudClaim() - require.NoError(rw.LookupWhere(ctx, &found, "oidc_method_id = ? and aud_claim = ?", []interface{}{tt.args.authMethodId, tt.args.aud})) + require.NoError(rw.LookupWhere(ctx, &found, "oidc_method_id = ? and aud_claim = ?", []any{tt.args.authMethodId, tt.args.aud})) assert.Equal(got, &found) } }) @@ -191,7 +191,7 @@ func TestAudClaim_Delete(t *testing.T) { } assert.Equal(tt.wantRowsDeleted, deletedRows) found := AllocAudClaim() - err = rw.LookupWhere(ctx, &found, "oidc_method_id = ? and aud_claim = ?", []interface{}{tt.AudClaim.OidcMethodId, tt.AudClaim.Aud}) + err = rw.LookupWhere(ctx, &found, "oidc_method_id = ? and aud_claim = ?", []any{tt.AudClaim.OidcMethodId, tt.AudClaim.Aud}) assert.True(errors.IsNotFoundError(err)) }) } diff --git a/internal/auth/oidc/auth_method.go b/internal/auth/oidc/auth_method.go index 901e5447ae..24206f8c9f 100644 --- a/internal/auth/oidc/auth_method.go +++ b/internal/auth/oidc/auth_method.go @@ -274,11 +274,11 @@ func (am *AuthMethod) isComplete(ctx context.Context) error { } type convertedValues struct { - Algs []interface{} - Auds []interface{} - Certs []interface{} - ClaimsScopes []interface{} - AccountClaimMaps []interface{} + Algs []any + Auds []any + Certs []any + ClaimsScopes []any + AccountClaimMaps []any } // convertValueObjects converts the embedded value objects. It will return an @@ -289,7 +289,7 @@ func (am *AuthMethod) convertValueObjects(ctx context.Context) (*convertedValues return nil, errors.New(ctx, errors.InvalidPublicId, op, "missing public id") } var err error - var addAlgs, addAuds, addCerts, addScopes, addAccountClaimMaps []interface{} + var addAlgs, addAuds, addCerts, addScopes, addAccountClaimMaps []any if addAlgs, err = am.convertSigningAlgs(ctx); err != nil { return nil, errors.Wrap(ctx, err, op) } @@ -317,12 +317,12 @@ func (am *AuthMethod) convertValueObjects(ctx context.Context) (*convertedValues // convertSigningAlgs converts the embedded signing algorithms from []string // to []interface{} where each slice element is a *SigningAlg. It will return an // error if the AuthMethod's public id is not set. -func (am *AuthMethod) convertSigningAlgs(ctx context.Context) ([]interface{}, error) { +func (am *AuthMethod) convertSigningAlgs(ctx context.Context) ([]any, error) { const op = "oidc.(AuthMethod).convertSigningAlgs" if am.PublicId == "" { return nil, errors.New(ctx, errors.InvalidPublicId, op, "missing public id") } - newInterfaces := make([]interface{}, 0, len(am.SigningAlgs)) + newInterfaces := make([]any, 0, len(am.SigningAlgs)) for _, a := range am.SigningAlgs { obj, err := NewSigningAlg(ctx, am.PublicId, Alg(a)) if err != nil { @@ -336,12 +336,12 @@ func (am *AuthMethod) convertSigningAlgs(ctx context.Context) ([]interface{}, er // convertAudClaims converts the embedded audience claims from []string // to []interface{} where each slice element is a *AudClaim. It will return an // error if the AuthMethod's public id is not set. -func (am *AuthMethod) convertAudClaims(ctx context.Context) ([]interface{}, error) { +func (am *AuthMethod) convertAudClaims(ctx context.Context) ([]any, error) { const op = "oidc.(AuthMethod).convertAudClaims" if am.PublicId == "" { return nil, errors.New(ctx, errors.InvalidPublicId, op, "missing public id") } - newInterfaces := make([]interface{}, 0, len(am.AudClaims)) + newInterfaces := make([]any, 0, len(am.AudClaims)) for _, a := range am.AudClaims { obj, err := NewAudClaim(ctx, am.PublicId, a) if err != nil { @@ -355,12 +355,12 @@ func (am *AuthMethod) convertAudClaims(ctx context.Context) ([]interface{}, erro // convertCertificates converts the embedded certificates from []string // to []interface{} where each slice element is a *Certificate. It will return an // error if the AuthMethod's public id is not set. -func (am *AuthMethod) convertCertificates(ctx context.Context) ([]interface{}, error) { +func (am *AuthMethod) convertCertificates(ctx context.Context) ([]any, error) { const op = "oidc.(AuthMethod).convertCertificates" if am.PublicId == "" { return nil, errors.New(ctx, errors.InvalidPublicId, op, "missing public id") } - newInterfaces := make([]interface{}, 0, len(am.Certificates)) + newInterfaces := make([]any, 0, len(am.Certificates)) for _, cert := range am.Certificates { obj, err := NewCertificate(ctx, am.PublicId, cert) if err != nil { @@ -374,12 +374,12 @@ func (am *AuthMethod) convertCertificates(ctx context.Context) ([]interface{}, e // convertClaimsScopes converts the embedded claims scopes from []string // to []interface{} where each slice element is a *ClaimsScope. It will return an // error if the AuthMethod's public id is not set. -func (am *AuthMethod) convertClaimsScopes(ctx context.Context) ([]interface{}, error) { +func (am *AuthMethod) convertClaimsScopes(ctx context.Context) ([]any, error) { const op = "oidc.(AuthMethod).convertClaimsScopes" if am.PublicId == "" { return nil, errors.New(ctx, errors.InvalidPublicId, op, "missing public id") } - newInterfaces := make([]interface{}, 0, len(am.ClaimsScopes)) + newInterfaces := make([]any, 0, len(am.ClaimsScopes)) for _, cs := range am.ClaimsScopes { obj, err := NewClaimsScope(ctx, am.PublicId, cs) if err != nil { @@ -394,12 +394,12 @@ func (am *AuthMethod) convertClaimsScopes(ctx context.Context) ([]interface{}, e // []string to []interface{} where each slice element is a *AccountClaimMap. It // will return an error if the AuthMethod's public id is not set or it can // convert the account claim maps. -func (am *AuthMethod) convertAccountClaimMaps(ctx context.Context) ([]interface{}, error) { +func (am *AuthMethod) convertAccountClaimMaps(ctx context.Context) ([]any, error) { const op = "oidc.(AuthMethod).convertAccountClaimMaps" if am.PublicId == "" { return nil, errors.New(ctx, errors.InvalidPublicId, op, "missing public id") } - newInterfaces := make([]interface{}, 0, len(am.AccountClaimMaps)) + newInterfaces := make([]any, 0, len(am.AccountClaimMaps)) const ( from = 0 to = 1 diff --git a/internal/auth/oidc/auth_method_test.go b/internal/auth/oidc/auth_method_test.go index a2f53db94a..595b5369b9 100644 --- a/internal/auth/oidc/auth_method_test.go +++ b/internal/auth/oidc/auth_method_test.go @@ -547,7 +547,7 @@ func Test_convertValueObjects(t *testing.T) { testPublicId := "test-id" testAlgs := []string{string(RS256), string(RS384)} - var testSigningAlgs []interface{} + var testSigningAlgs []any for _, a := range []Alg{RS256, RS384} { obj, err := NewSigningAlg(ctx, testPublicId, Alg(a)) require.NoError(t, err) @@ -555,7 +555,7 @@ func Test_convertValueObjects(t *testing.T) { } testAuds := []string{"alice", "eve"} - var testAudiences []interface{} + var testAudiences []any for _, a := range testAuds { obj, err := NewAudClaim(ctx, testPublicId, a) require.NoError(t, err) @@ -566,10 +566,10 @@ func Test_convertValueObjects(t *testing.T) { testCerts := []string{pem} c, err := NewCertificate(ctx, testPublicId, pem) require.NoError(t, err) - testCertificates := []interface{}{c} + testCertificates := []any{c} testScopes := []string{"profile", "email"} - testClaimsScopes := make([]interface{}, 0, len(testScopes)) + testClaimsScopes := make([]any, 0, len(testScopes)) for _, s := range testScopes { obj, err := NewClaimsScope(ctx, testPublicId, s) require.NoError(t, err) @@ -577,7 +577,7 @@ func Test_convertValueObjects(t *testing.T) { } testClaimMaps := []string{"oid=sub", "display_name=name"} - testAccountClaimMaps := make([]interface{}, 0, len(testClaimMaps)) + testAccountClaimMaps := make([]any, 0, len(testClaimMaps)) acms, err := ParseAccountClaimMaps(ctx, testClaimMaps...) require.NoError(t, err) for _, m := range acms { @@ -707,7 +707,7 @@ func Test_convertValueObjects(t *testing.T) { } } -type converted []interface{} +type converted []any func (a converted) Len() int { return len(a) } func (a converted) Swap(i, j int) { a[i], a[j] = a[j], a[i] } diff --git a/internal/auth/oidc/certificate_test.go b/internal/auth/oidc/certificate_test.go index 93fe70ee68..35560383e1 100644 --- a/internal/auth/oidc/certificate_test.go +++ b/internal/auth/oidc/certificate_test.go @@ -112,7 +112,7 @@ func TestCertificate_Create(t *testing.T) { assert.NoError(err) } found := AllocCertificate() - require.NoError(rw.LookupWhere(ctx, &found, "oidc_method_id = ? and certificate = ?", []interface{}{tt.args.authMethodId, tt.args.certificate})) + require.NoError(rw.LookupWhere(ctx, &found, "oidc_method_id = ? and certificate = ?", []any{tt.args.authMethodId, tt.args.certificate})) assert.Equal(got, &found) } }) @@ -196,7 +196,7 @@ func TestCertificate_Delete(t *testing.T) { } assert.Equal(tt.wantRowsDeleted, deletedRows) found := AllocCertificate() - err = rw.LookupWhere(ctx, &found, "oidc_method_id = ? and certificate = ?", []interface{}{tt.Certificate.OidcMethodId, tt.Certificate.Cert}) + err = rw.LookupWhere(ctx, &found, "oidc_method_id = ? and certificate = ?", []any{tt.Certificate.OidcMethodId, tt.Certificate.Cert}) assert.True(errors.IsNotFoundError(err)) }) } diff --git a/internal/auth/oidc/claims_scope_test.go b/internal/auth/oidc/claims_scope_test.go index a1e31c5c0b..10423bbf64 100644 --- a/internal/auth/oidc/claims_scope_test.go +++ b/internal/auth/oidc/claims_scope_test.go @@ -115,7 +115,7 @@ func TestClaimsScope_Create(t *testing.T) { } assert.NoError(err) found := AllocClaimsScope() - require.NoError(rw.LookupWhere(ctx, &found, "oidc_method_id = ? and scope = ?", []interface{}{tt.args.authMethodId, tt.args.claimsScope})) + require.NoError(rw.LookupWhere(ctx, &found, "oidc_method_id = ? and scope = ?", []any{tt.args.authMethodId, tt.args.claimsScope})) } }) } @@ -192,7 +192,7 @@ func TestClaimsScope_Delete(t *testing.T) { } assert.Equal(tt.wantRowsDeleted, deletedRows) found := AllocClaimsScope() - err = rw.LookupWhere(ctx, &found, "oidc_method_id = ? and scope = ?", []interface{}{tt.claimsScope.OidcMethodId, tt.claimsScope.Scope}) + err = rw.LookupWhere(ctx, &found, "oidc_method_id = ? and scope = ?", []any{tt.claimsScope.OidcMethodId, tt.claimsScope.Scope}) assert.True(errors.IsNotFoundError(err)) }) } diff --git a/internal/auth/oidc/immutable_fields_test.go b/internal/auth/oidc/immutable_fields_test.go index 145c6f71cb..02949a6535 100644 --- a/internal/auth/oidc/immutable_fields_test.go +++ b/internal/auth/oidc/immutable_fields_test.go @@ -105,7 +105,7 @@ func TestAudClaim_ImmutableFields(t *testing.T) { WithApiUrl(TestConvertToUrls(t, "https://api.com")[0]), WithAudClaims("alice.com")) new := AllocAudClaim() - require.NoError(t, rw.LookupWhere(ctx, &new, "oidc_method_id = ? and aud_claim = ?", []interface{}{am.PublicId, "alice.com"})) + require.NoError(t, rw.LookupWhere(ctx, &new, "oidc_method_id = ? and aud_claim = ?", []any{am.PublicId, "alice.com"})) tests := []struct { name string @@ -147,7 +147,7 @@ func TestAudClaim_ImmutableFields(t *testing.T) { orig := new.Clone() orig.SetTableName(defaultAuthMethodTableName) - require.NoError(rw.LookupWhere(ctx, &new, "oidc_method_id = ? and aud_claim = ?", []interface{}{orig.OidcMethodId, orig.Aud})) + require.NoError(rw.LookupWhere(ctx, &new, "oidc_method_id = ? and aud_claim = ?", []any{orig.OidcMethodId, orig.Aud})) require.NoError(err) @@ -158,7 +158,7 @@ func TestAudClaim_ImmutableFields(t *testing.T) { after := new.Clone() after.SetTableName(defaultAuthMethodTableName) - require.NoError(rw.LookupWhere(ctx, &new, "oidc_method_id = ? and aud_claim = ?", []interface{}{after.OidcMethodId, after.Aud})) + require.NoError(rw.LookupWhere(ctx, &new, "oidc_method_id = ? and aud_claim = ?", []any{after.OidcMethodId, after.Aud})) assert.True(proto.Equal(orig, after)) }) @@ -186,7 +186,7 @@ func TestCertificate_ImmutableFields(t *testing.T) { WithApiUrl(TestConvertToUrls(t, "https://api.com")[0]), WithCertificates(x509)) new := AllocCertificate() - require.NoError(t, rw.LookupWhere(ctx, &new, "oidc_method_id = ? and certificate = ?", []interface{}{am.PublicId, pem})) + require.NoError(t, rw.LookupWhere(ctx, &new, "oidc_method_id = ? and certificate = ?", []any{am.PublicId, pem})) tests := []struct { name string @@ -228,7 +228,7 @@ func TestCertificate_ImmutableFields(t *testing.T) { orig := new.Clone() orig.SetTableName(defaultAuthMethodTableName) - require.NoError(rw.LookupWhere(ctx, &new, "oidc_method_id = ? and certificate = ?", []interface{}{orig.OidcMethodId, orig.Cert})) + require.NoError(rw.LookupWhere(ctx, &new, "oidc_method_id = ? and certificate = ?", []any{orig.OidcMethodId, orig.Cert})) require.NoError(err) @@ -239,7 +239,7 @@ func TestCertificate_ImmutableFields(t *testing.T) { after := new.Clone() after.SetTableName(defaultAuthMethodTableName) - require.NoError(rw.LookupWhere(ctx, &new, "oidc_method_id = ? and certificate = ?", []interface{}{after.OidcMethodId, after.Cert})) + require.NoError(rw.LookupWhere(ctx, &new, "oidc_method_id = ? and certificate = ?", []any{after.OidcMethodId, after.Cert})) assert.True(proto.Equal(orig, after)) }) @@ -263,7 +263,7 @@ func TestSigningAlg_ImmutableFields(t *testing.T) { WithApiUrl(TestConvertToUrls(t, "https://api.com")[0]), WithSigningAlgs(RS256)) new := AllocSigningAlg() - require.NoError(t, rw.LookupWhere(ctx, &new, "oidc_method_id = ? and signing_alg_name = ?", []interface{}{am.PublicId, RS256})) + require.NoError(t, rw.LookupWhere(ctx, &new, "oidc_method_id = ? and signing_alg_name = ?", []any{am.PublicId, RS256})) tests := []struct { name string @@ -305,7 +305,7 @@ func TestSigningAlg_ImmutableFields(t *testing.T) { orig := new.Clone() orig.SetTableName(defaultAuthMethodTableName) - require.NoError(rw.LookupWhere(ctx, &new, "oidc_method_id = ? and signing_alg_name = ?", []interface{}{orig.OidcMethodId, orig.Alg})) + require.NoError(rw.LookupWhere(ctx, &new, "oidc_method_id = ? and signing_alg_name = ?", []any{orig.OidcMethodId, orig.Alg})) require.NoError(err) @@ -316,7 +316,7 @@ func TestSigningAlg_ImmutableFields(t *testing.T) { after := new.Clone() after.SetTableName(defaultAuthMethodTableName) - require.NoError(rw.LookupWhere(ctx, &new, "oidc_method_id = ? and signing_alg_name = ?", []interface{}{after.OidcMethodId, after.Alg})) + require.NoError(rw.LookupWhere(ctx, &new, "oidc_method_id = ? and signing_alg_name = ?", []any{after.OidcMethodId, after.Alg})) assert.True(proto.Equal(orig, after)) }) diff --git a/internal/auth/oidc/repository_account.go b/internal/auth/oidc/repository_account.go index 2d68acf8f5..0847bd6561 100644 --- a/internal/auth/oidc/repository_account.go +++ b/internal/auth/oidc/repository_account.go @@ -142,7 +142,7 @@ func (r *Repository) ListAccounts(ctx context.Context, withAuthMethodId string, limit = opts.withLimit } var accts []*Account - err := r.reader.SearchWhere(ctx, &accts, "auth_method_id = ?", []interface{}{withAuthMethodId}, db.WithLimit(limit)) + err := r.reader.SearchWhere(ctx, &accts, "auth_method_id = ?", []any{withAuthMethodId}, db.WithLimit(limit)) if err != nil { return nil, errors.Wrap(ctx, err, op) } @@ -232,7 +232,7 @@ func (r *Repository) UpdateAccount(ctx context.Context, scopeId string, a *Accou } var dbMask, nullFields []string dbMask, nullFields = dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ NameField: a.Name, DescriptionField: a.Description, }, diff --git a/internal/auth/oidc/repository_auth_method.go b/internal/auth/oidc/repository_auth_method.go index 3c55ca707e..c5c2c391fa 100644 --- a/internal/auth/oidc/repository_auth_method.go +++ b/internal/auth/oidc/repository_auth_method.go @@ -23,7 +23,7 @@ var _ oplog.ReplayableMessage = (*Account)(nil) var _ proto.Message = (*Account)(nil) // upsertAccount will create/update account using claims from the user's ID and Access Tokens. -func (r *Repository) upsertAccount(ctx context.Context, am *AuthMethod, IdTokenClaims, AccessTokenClaims map[string]interface{}) (*Account, error) { +func (r *Repository) upsertAccount(ctx context.Context, am *AuthMethod, IdTokenClaims, AccessTokenClaims map[string]any) (*Account, error) { const op = "oidc.(Repository).upsertAccount" if am == nil || am.AuthMethod == nil { return nil, errors.New(ctx, errors.InvalidParameter, op, "missing auth method") @@ -74,7 +74,7 @@ func (r *Repository) upsertAccount(ctx context.Context, am *AuthMethod, IdTokenC } columns := []string{"public_id", "auth_method_id", "issuer", "subject"} - values := []interface{}{ + values := []any{ sql.Named("1", pubId), sql.Named("2", am.PublicId), sql.Named("3", iss), @@ -110,7 +110,7 @@ func (r *Repository) upsertAccount(ctx context.Context, am *AuthMethod, IdTokenC return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to create new acct for oplog")) } - var foundName interface{} + var foundName any switch { case AccessTokenClaims[fromName] != nil: foundName = AccessTokenClaims[fromName] @@ -128,7 +128,7 @@ func (r *Repository) upsertAccount(ctx context.Context, am *AuthMethod, IdTokenC nullMasks = append(nullMasks, NameField) } - var foundEmail interface{} + var foundEmail any switch { case AccessTokenClaims[fromEmail] != nil: foundEmail = AccessTokenClaims[fromEmail] @@ -184,7 +184,7 @@ func (r *Repository) upsertAccount(ctx context.Context, am *AuthMethod, IdTokenC if rowCnt > 1 { return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("expected 1 row but got: %d", rowCnt)) } - if err := reader.LookupWhere(ctx, &updatedAcct, "auth_method_id = ? and issuer = ? and subject = ?", []interface{}{am.PublicId, iss, sub}); err != nil { + if err := reader.LookupWhere(ctx, &updatedAcct, "auth_method_id = ? and issuer = ? and subject = ?", []any{am.PublicId, iss, sub}); err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to look up auth oidc account for: %s / %s / %s", am.PublicId, iss, sub))) } // include the version incase of predictable account public ids based on a calculation using authmethod id and subject @@ -243,11 +243,11 @@ func upsertOplog(ctx context.Context, w db.Writer, oplogWrapper wrapping.Wrapper return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get ticket")) } metadata := acct.oplog(operation, scopeId) - acctAsReplayable, ok := interface{}(acct).(oplog.ReplayableMessage) + acctAsReplayable, ok := any(acct).(oplog.ReplayableMessage) if !ok { return errors.New(ctx, errors.Internal, op, "account is not replayable") } - acctAsProto, ok := interface{}(acct).(proto.Message) + acctAsProto, ok := any(acct).(proto.Message) if !ok { return errors.New(ctx, errors.Internal, op, "account is not a proto message") } diff --git a/internal/auth/oidc/repository_auth_method_read.go b/internal/auth/oidc/repository_auth_method_read.go index 4448731ee7..5b2570197c 100644 --- a/internal/auth/oidc/repository_auth_method_read.go +++ b/internal/auth/oidc/repository_auth_method_read.go @@ -98,7 +98,7 @@ func (r *Repository) getAuthMethods(ctx context.Context, authMethodId string, sc } } - var args []interface{} + var args []any var where []string switch { case authMethodId != "": diff --git a/internal/auth/oidc/repository_auth_method_test.go b/internal/auth/oidc/repository_auth_method_test.go index 46696811ac..b7506eadbd 100644 --- a/internal/auth/oidc/repository_auth_method_test.go +++ b/internal/auth/oidc/repository_auth_method_test.go @@ -49,8 +49,8 @@ func Test_upsertAccount(t *testing.T) { tests := []struct { name string am *AuthMethod - idClaims map[string]interface{} - atClaims map[string]interface{} + idClaims map[string]any + atClaims map[string]any wantAcct *Account wantErrMatch *errors.Template wantErrContains string @@ -58,8 +58,8 @@ func Test_upsertAccount(t *testing.T) { { name: "success-defaults", am: amActivePriv, - idClaims: map[string]interface{}{"iss": "https://alice-active-priv.com", "sub": "success-defaults"}, - atClaims: map[string]interface{}{}, + idClaims: map[string]any{"iss": "https://alice-active-priv.com", "sub": "success-defaults"}, + atClaims: map[string]any{}, wantAcct: &Account{Account: &store.Account{ AuthMethodId: amActivePriv.PublicId, Issuer: "https://alice-active-priv.com", @@ -71,8 +71,8 @@ func Test_upsertAccount(t *testing.T) { { name: "success-atTk-full-name-and-email", am: amActivePriv, - idClaims: map[string]interface{}{"iss": "https://alice-active-priv.com", "sub": "success-atTk-full-name-and-email"}, - atClaims: map[string]interface{}{"name": "alice eve-smith", "email": "alice@alice.com"}, + idClaims: map[string]any{"iss": "https://alice-active-priv.com", "sub": "success-atTk-full-name-and-email"}, + atClaims: map[string]any{"name": "alice eve-smith", "email": "alice@alice.com"}, wantAcct: &Account{Account: &store.Account{ AuthMethodId: amActivePriv.PublicId, Issuer: "https://alice-active-priv.com", @@ -86,8 +86,8 @@ func Test_upsertAccount(t *testing.T) { { name: "success-idTk-full-name-and-email", am: amActivePriv, - idClaims: map[string]interface{}{"iss": "https://alice-active-priv.com", "sub": "success-idTk-full-name-and-email", "name": "alice eve-smith", "email": "alice@alice.com"}, - atClaims: map[string]interface{}{}, + idClaims: map[string]any{"iss": "https://alice-active-priv.com", "sub": "success-idTk-full-name-and-email", "name": "alice eve-smith", "email": "alice@alice.com"}, + atClaims: map[string]any{}, wantAcct: &Account{Account: &store.Account{ AuthMethodId: amActivePriv.PublicId, Issuer: "https://alice-active-priv.com", @@ -101,8 +101,8 @@ func Test_upsertAccount(t *testing.T) { { name: "success-map-idTk", am: amWithMapping, - idClaims: map[string]interface{}{"iss": "https://alice-active-priv.com", "sub": "success-defaults", "oid": "success-map"}, - atClaims: map[string]interface{}{}, + idClaims: map[string]any{"iss": "https://alice-active-priv.com", "sub": "success-defaults", "oid": "success-map"}, + atClaims: map[string]any{}, wantAcct: &Account{Account: &store.Account{ AuthMethodId: amWithMapping.PublicId, Issuer: "https://alice-active-priv.com", @@ -114,62 +114,62 @@ func Test_upsertAccount(t *testing.T) { { name: "non-existent-auth-method-scope-id", am: func() *AuthMethod { cp := amActivePriv.Clone(); cp.ScopeId = "non-existent-scope-id"; return cp }(), - idClaims: map[string]interface{}{"iss": "https://alice.com", "sub": "non-existent-auth-method-scope-id"}, - atClaims: map[string]interface{}{}, + idClaims: map[string]any{"iss": "https://alice.com", "sub": "non-existent-auth-method-scope-id"}, + atClaims: map[string]any{}, wantErrMatch: errors.T(errors.Unknown), wantErrContains: "unable to get oplog wrapper", }, { name: "non-parsable-issuer", am: amActivePriv, - idClaims: map[string]interface{}{"iss": ":::::alice.com", "sub": "non-parsable-issuer"}, - atClaims: map[string]interface{}{}, + idClaims: map[string]any{"iss": ":::::alice.com", "sub": "non-parsable-issuer"}, + atClaims: map[string]any{}, wantErrMatch: errors.T(errors.Unknown), wantErrContains: "unable to parse issuer", }, { name: "empty-sub", am: amActivePriv, - idClaims: map[string]interface{}{"iss": "https://alice.com", "sub": ""}, - atClaims: map[string]interface{}{}, + idClaims: map[string]any{"iss": "https://alice.com", "sub": ""}, + atClaims: map[string]any{}, wantErrMatch: errors.T(errors.Unknown), wantErrContains: "missing subject", }, { name: "empty-issuer", am: amActivePriv, - idClaims: map[string]interface{}{"iss": "", "sub": "bad-issuer"}, - atClaims: map[string]interface{}{}, + idClaims: map[string]any{"iss": "", "sub": "bad-issuer"}, + atClaims: map[string]any{}, wantErrMatch: errors.T(errors.Unknown), wantErrContains: "missing issuer", }, { name: "missing-id-token-issuer", am: amActivePriv, - idClaims: map[string]interface{}{}, - atClaims: map[string]interface{}{}, + idClaims: map[string]any{}, + atClaims: map[string]any{}, wantErrMatch: errors.T(errors.Unknown), wantErrContains: "issuer is not present in ID Token", }, { name: "missing-id-token-sub", am: amActivePriv, - idClaims: map[string]interface{}{"iss": "https://alice.com"}, - atClaims: map[string]interface{}{}, + idClaims: map[string]any{"iss": "https://alice.com"}, + atClaims: map[string]any{}, wantErrMatch: errors.T(errors.Unknown), wantErrContains: "to account subject and it is not present in ID Token", }, { name: "missing-id-token-claims", am: amActivePriv, - atClaims: map[string]interface{}{}, + atClaims: map[string]any{}, wantErrMatch: errors.T(errors.Unknown), wantErrContains: "missing ID Token claims", }, { name: "missing-access-token-claims", am: amActivePriv, - idClaims: map[string]interface{}{}, + idClaims: map[string]any{}, wantErrMatch: errors.T(errors.Unknown), wantErrContains: "missing Access Token claims", }, diff --git a/internal/auth/oidc/repository_auth_method_update.go b/internal/auth/oidc/repository_auth_method_update.go index 39a0728b2e..4598830d10 100644 --- a/internal/auth/oidc/repository_auth_method_update.go +++ b/internal/auth/oidc/repository_auth_method_update.go @@ -92,7 +92,7 @@ func (r *Repository) UpdateAuthMethod(ctx context.Context, am *AuthMethod, versi } dbMask, nullFields := dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ NameField: am.Name, DescriptionField: am.Description, IssuerField: am.Issuer, @@ -435,27 +435,27 @@ func validVoName(name voName) bool { } // factoryFunc defines a func type for value object factories -type factoryFunc func(ctx context.Context, publicId string, i interface{}) (interface{}, error) +type factoryFunc func(ctx context.Context, publicId string, i any) (any, error) // supportedFactories are the currently supported factoryFunc for value objects var supportedFactories = map[voName]factoryFunc{ - SigningAlgVO: func(ctx context.Context, publicId string, i interface{}) (interface{}, error) { + SigningAlgVO: func(ctx context.Context, publicId string, i any) (any, error) { str := fmt.Sprintf("%s", i) return NewSigningAlg(ctx, publicId, Alg(str)) }, - CertificateVO: func(ctx context.Context, publicId string, i interface{}) (interface{}, error) { + CertificateVO: func(ctx context.Context, publicId string, i any) (any, error) { str := fmt.Sprintf("%s", i) return NewCertificate(ctx, publicId, str) }, - AudClaimVO: func(ctx context.Context, publicId string, i interface{}) (interface{}, error) { + AudClaimVO: func(ctx context.Context, publicId string, i any) (any, error) { str := fmt.Sprintf("%s", i) return NewAudClaim(ctx, publicId, str) }, - ClaimsScopesVO: func(ctx context.Context, publicId string, i interface{}) (interface{}, error) { + ClaimsScopesVO: func(ctx context.Context, publicId string, i any) (any, error) { str := fmt.Sprintf("%s", i) return NewClaimsScope(ctx, publicId, str) }, - AccountClaimMapsVO: func(ctx context.Context, publicId string, i interface{}) (interface{}, error) { + AccountClaimMapsVO: func(ctx context.Context, publicId string, i any) (any, error) { const op = "oidc.AccountClaimMapsFactory" str := fmt.Sprintf("%s", i) acm, err := ParseAccountClaimMaps(ctx, str) @@ -487,7 +487,7 @@ func valueObjectChanges( oldVOs, dbMask, nullFields []string, -) (add []interface{}, del []interface{}, e error) { +) (add []any, del []any, e error) { const op = "valueObjectChanges" if publicId == "" { return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing public id") @@ -518,10 +518,10 @@ func valueObjectChanges( for _, a := range oldVOs { foundVOs[a] = true } - var adds []interface{} - var deletes []interface{} + var adds []any + var deletes []any if strutil.StrListContains(nullFields, string(valueObjectName)) { - deletes = make([]interface{}, 0, len(oldVOs)) + deletes = make([]any, 0, len(oldVOs)) for _, v := range oldVOs { deleteObj, err := factory(ctx, publicId, v) if err != nil { @@ -532,7 +532,7 @@ func valueObjectChanges( } } if strutil.StrListContains(dbMask, string(valueObjectName)) { - adds = make([]interface{}, 0, len(newVOs)) + adds = make([]any, 0, len(newVOs)) for _, v := range newVOs { if _, ok := foundVOs[v]; ok { delete(foundVOs, v) diff --git a/internal/auth/oidc/repository_auth_method_update_test.go b/internal/auth/oidc/repository_auth_method_update_test.go index bd1506ba14..484680bd38 100644 --- a/internal/auth/oidc/repository_auth_method_update_test.go +++ b/internal/auth/oidc/repository_auth_method_update_test.go @@ -784,8 +784,8 @@ func Test_valueObjectChanges(t *testing.T) { old []string dbMask []string nullFields []string - wantAdd []interface{} - wantDel []interface{} + wantAdd []any + wantDel []any wantErrMatch *errors.Template }{ { @@ -795,21 +795,21 @@ func Test_valueObjectChanges(t *testing.T) { new: []string{"ES256", "ES384"}, old: []string{"RS256", "RS384", "RS512"}, dbMask: []string{string(SigningAlgVO)}, - wantAdd: func() []interface{} { + wantAdd: func() []any { a, err := NewSigningAlg(ctx, "am-public-id", ES256) require.NoError(t, err) a2, err := NewSigningAlg(ctx, "am-public-id", ES384) require.NoError(t, err) - return []interface{}{a, a2} + return []any{a, a2} }(), - wantDel: func() []interface{} { + wantDel: func() []any { a, err := NewSigningAlg(ctx, "am-public-id", RS256) require.NoError(t, err) a2, err := NewSigningAlg(ctx, "am-public-id", RS384) require.NoError(t, err) a3, err := NewSigningAlg(ctx, "am-public-id", RS512) require.NoError(t, err) - return []interface{}{a, a2, a3} + return []any{a, a2, a3} }(), }, { @@ -819,17 +819,17 @@ func Test_valueObjectChanges(t *testing.T) { new: []string{pem1, pem2}, old: []string{pem3}, dbMask: []string{string(CertificateVO)}, - wantAdd: func() []interface{} { + wantAdd: func() []any { c, err := NewCertificate(ctx, "am-public-id", pem1) require.NoError(t, err) c2, err := NewCertificate(ctx, "am-public-id", pem2) require.NoError(t, err) - return []interface{}{c, c2} + return []any{c, c2} }(), - wantDel: func() []interface{} { + wantDel: func() []any { c, err := NewCertificate(ctx, "am-public-id", pem3) require.NoError(t, err) - return []interface{}{c} + return []any{c} }(), }, { @@ -839,21 +839,21 @@ func Test_valueObjectChanges(t *testing.T) { new: []string{"new-aud1", "new-aud2"}, old: []string{"old-aud1", "old-aud2", "old-aud3"}, dbMask: []string{string(AudClaimVO)}, - wantAdd: func() []interface{} { + wantAdd: func() []any { a, err := NewAudClaim(ctx, "am-public-id", "new-aud1") require.NoError(t, err) a2, err := NewAudClaim(ctx, "am-public-id", "new-aud2") require.NoError(t, err) - return []interface{}{a, a2} + return []any{a, a2} }(), - wantDel: func() []interface{} { + wantDel: func() []any { a, err := NewAudClaim(ctx, "am-public-id", "old-aud1") require.NoError(t, err) a2, err := NewAudClaim(ctx, "am-public-id", "old-aud2") require.NoError(t, err) a3, err := NewAudClaim(ctx, "am-public-id", "old-aud3") require.NoError(t, err) - return []interface{}{a, a2, a3} + return []any{a, a2, a3} }(), }, @@ -864,14 +864,14 @@ func Test_valueObjectChanges(t *testing.T) { new: nil, old: []string{"old-aud1", "old-aud2", "old-aud3"}, nullFields: []string{string(AudClaimVO)}, - wantDel: func() []interface{} { + wantDel: func() []any { a, err := NewAudClaim(ctx, "am-public-id", "old-aud1") require.NoError(t, err) a2, err := NewAudClaim(ctx, "am-public-id", "old-aud2") require.NoError(t, err) a3, err := NewAudClaim(ctx, "am-public-id", "old-aud3") require.NoError(t, err) - return []interface{}{a, a2, a3} + return []any{a, a2, a3} }(), }, { @@ -881,21 +881,21 @@ func Test_valueObjectChanges(t *testing.T) { new: []string{"new-scope1", "new-scope2"}, old: []string{"old-scope1", "old-scope2", "old-scope3"}, dbMask: []string{string(ClaimsScopesVO)}, - wantAdd: func() []interface{} { + wantAdd: func() []any { cs, err := NewClaimsScope(ctx, "am-public-id", "new-scope1") require.NoError(t, err) cs2, err := NewClaimsScope(ctx, "am-public-id", "new-scope2") require.NoError(t, err) - return []interface{}{cs, cs2} + return []any{cs, cs2} }(), - wantDel: func() []interface{} { + wantDel: func() []any { cs, err := NewClaimsScope(ctx, "am-public-id", "old-scope1") require.NoError(t, err) cs2, err := NewClaimsScope(ctx, "am-public-id", "old-scope2") require.NoError(t, err) cs3, err := NewClaimsScope(ctx, "am-public-id", "old-scope3") require.NoError(t, err) - return []interface{}{cs, cs2, cs3} + return []any{cs, cs2, cs3} }(), }, { @@ -905,14 +905,14 @@ func Test_valueObjectChanges(t *testing.T) { new: nil, old: []string{"old-scope1", "old-scope2", "old-scope3"}, nullFields: []string{string(ClaimsScopesVO)}, - wantDel: func() []interface{} { + wantDel: func() []any { cs, err := NewClaimsScope(ctx, "am-public-id", "old-scope1") require.NoError(t, err) cs2, err := NewClaimsScope(ctx, "am-public-id", "old-scope2") require.NoError(t, err) cs3, err := NewClaimsScope(ctx, "am-public-id", "old-scope3") require.NoError(t, err) - return []interface{}{cs, cs2, cs3} + return []any{cs, cs2, cs3} }(), }, { @@ -921,14 +921,14 @@ func Test_valueObjectChanges(t *testing.T) { new: nil, old: []string{"old-aud1", "old-aud2", "old-aud3"}, nullFields: []string{string(AudClaimVO)}, - wantDel: func() []interface{} { + wantDel: func() []any { a, err := NewAudClaim(ctx, "am-public-id", "old-aud1") require.NoError(t, err) a2, err := NewAudClaim(ctx, "am-public-id", "old-aud2") require.NoError(t, err) a3, err := NewAudClaim(ctx, "am-public-id", "old-aud3") require.NoError(t, err) - return []interface{}{a, a2, a3} + return []any{a, a2, a3} }(), wantErrMatch: errors.T(errors.InvalidParameter), }, @@ -939,14 +939,14 @@ func Test_valueObjectChanges(t *testing.T) { new: nil, old: []string{"old-aud1", "old-aud2", "old-aud3"}, nullFields: []string{string(AudClaimVO)}, - wantDel: func() []interface{} { + wantDel: func() []any { a, err := NewAudClaim(ctx, "am-public-id", "old-aud1") require.NoError(t, err) a2, err := NewAudClaim(ctx, "am-public-id", "old-aud2") require.NoError(t, err) a3, err := NewAudClaim(ctx, "am-public-id", "old-aud3") require.NoError(t, err) - return []interface{}{a, a2, a3} + return []any{a, a2, a3} }(), wantErrMatch: errors.T(errors.InvalidParameter), }, @@ -957,21 +957,21 @@ func Test_valueObjectChanges(t *testing.T) { new: []string{"ES256", "ES256"}, old: []string{"RS256", "RS384", "RS512"}, dbMask: []string{string(SigningAlgVO)}, - wantAdd: func() []interface{} { + wantAdd: func() []any { a, err := NewSigningAlg(ctx, "am-public-id", ES256) require.NoError(t, err) a2, err := NewSigningAlg(ctx, "am-public-id", ES384) require.NoError(t, err) - return []interface{}{a, a2} + return []any{a, a2} }(), - wantDel: func() []interface{} { + wantDel: func() []any { a, err := NewSigningAlg(ctx, "am-public-id", RS256) require.NoError(t, err) a2, err := NewSigningAlg(ctx, "am-public-id", RS384) require.NoError(t, err) a3, err := NewSigningAlg(ctx, "am-public-id", RS512) require.NoError(t, err) - return []interface{}{a, a2, a3} + return []any{a, a2, a3} }(), wantErrMatch: errors.T(errors.InvalidParameter), }, @@ -982,21 +982,21 @@ func Test_valueObjectChanges(t *testing.T) { new: []string{"ES256", "ES384"}, old: []string{"RS256", "RS256", "RS512"}, dbMask: []string{string(SigningAlgVO)}, - wantAdd: func() []interface{} { + wantAdd: func() []any { a, err := NewSigningAlg(ctx, "am-public-id", ES256) require.NoError(t, err) a2, err := NewSigningAlg(ctx, "am-public-id", ES384) require.NoError(t, err) - return []interface{}{a, a2} + return []any{a, a2} }(), - wantDel: func() []interface{} { + wantDel: func() []any { a, err := NewSigningAlg(ctx, "am-public-id", RS256) require.NoError(t, err) a2, err := NewSigningAlg(ctx, "am-public-id", RS384) require.NoError(t, err) a3, err := NewSigningAlg(ctx, "am-public-id", RS512) require.NoError(t, err) - return []interface{}{a, a2, a3} + return []any{a, a2, a3} }(), wantErrMatch: errors.T(errors.InvalidParameter), }, diff --git a/internal/auth/oidc/repository_managed_group.go b/internal/auth/oidc/repository_managed_group.go index 1e64f98331..7a3a2e16ed 100644 --- a/internal/auth/oidc/repository_managed_group.go +++ b/internal/auth/oidc/repository_managed_group.go @@ -106,7 +106,7 @@ func (r *Repository) ListManagedGroups(ctx context.Context, withAuthMethodId str limit = opts.withLimit } var mgs []*ManagedGroup - err := r.reader.SearchWhere(ctx, &mgs, "auth_method_id = ?", []interface{}{withAuthMethodId}, db.WithLimit(limit)) + err := r.reader.SearchWhere(ctx, &mgs, "auth_method_id = ?", []any{withAuthMethodId}, db.WithLimit(limit)) if err != nil { return nil, errors.Wrap(ctx, err, op) } @@ -198,7 +198,7 @@ func (r *Repository) UpdateManagedGroup(ctx context.Context, scopeId string, mg } var dbMask, nullFields []string dbMask, nullFields = dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ NameField: mg.Name, DescriptionField: mg.Description, FilterField: mg.Filter, diff --git a/internal/auth/oidc/repository_managed_group_members.go b/internal/auth/oidc/repository_managed_group_members.go index 91931122f8..b21f94270d 100644 --- a/internal/auth/oidc/repository_managed_group_members.go +++ b/internal/auth/oidc/repository_managed_group_members.go @@ -114,7 +114,7 @@ func (r *Repository) SetManagedGroupMemberships(ctx context.Context, am *AuthMet } // Figure out which ones to delete and which ones we already have - toDelete := make([]interface{}, 0, len(mgs)) + toDelete := make([]any, 0, len(mgs)) for _, currMg := range currentMemberships { currMgId := currMg.ManagedGroupId if newMgPublicIds[currMgId] { @@ -158,7 +158,7 @@ func (r *Repository) SetManagedGroupMemberships(ctx context.Context, am *AuthMet if len(newMgPublicIds) > 0 { metadata["op-type"] = append(metadata["op-type"], oplog.OpType_OP_TYPE_CREATE.String()) addOplogMsgs := make([]*oplog.Message, 0, len(newMgPublicIds)) - toAdd := make([]interface{}, 0, len(newMgPublicIds)) + toAdd := make([]any, 0, len(newMgPublicIds)) for mgId := range newMgPublicIds { newMg := AllocManagedGroupMemberAccount() newMg.ManagedGroupId = mgId @@ -208,7 +208,7 @@ func (r *Repository) ListManagedGroupMembershipsByMember(ctx context.Context, wi reader = opts.withReader } var mgs []*ManagedGroupMemberAccount - err := reader.SearchWhere(ctx, &mgs, "member_id = ?", []interface{}{withAcctId}, db.WithLimit(limit)) + err := reader.SearchWhere(ctx, &mgs, "member_id = ?", []any{withAcctId}, db.WithLimit(limit)) if err != nil { return nil, errors.Wrap(ctx, err, op) } @@ -233,7 +233,7 @@ func (r *Repository) ListManagedGroupMembershipsByGroup(ctx context.Context, wit reader = opts.withReader } var mgs []*ManagedGroupMemberAccount - err := reader.SearchWhere(ctx, &mgs, "managed_group_id = ?", []interface{}{withGroupId}, db.WithLimit(limit)) + err := reader.SearchWhere(ctx, &mgs, "managed_group_id = ?", []any{withGroupId}, db.WithLimit(limit)) if err != nil { return nil, errors.Wrap(ctx, err, op) } diff --git a/internal/auth/oidc/service_callback.go b/internal/auth/oidc/service_callback.go index 9a95eacaef..c75d63bbdd 100644 --- a/internal/auth/oidc/service_callback.go +++ b/internal/auth/oidc/service_callback.go @@ -165,8 +165,8 @@ func Callback( // okay, now we need some claims from both the ID Token and userinfo, so we can // upsert an auth account - idTkClaims := map[string]interface{}{} // intentionally, NOT nil for call to upsertAccount(...) - userInfoClaims := map[string]interface{}{} // intentionally, NOT nil for call to upsertAccount(...) + idTkClaims := map[string]any{} // intentionally, NOT nil for call to upsertAccount(...) + userInfoClaims := map[string]any{} // intentionally, NOT nil for call to upsertAccount(...) if err := tk.IDToken().Claims(&idTkClaims); err != nil { return "", errors.New(ctx, errors.Unknown, op, "unable to parse ID Token claims", errors.WithWrap(err)) @@ -195,7 +195,7 @@ func Callback( } if len(mgs) > 0 { matchedMgs := make([]*ManagedGroup, 0, len(mgs)) - evalData := map[string]interface{}{ + evalData := map[string]any{ "token": idTkClaims, "userinfo": userInfoClaims, } diff --git a/internal/auth/oidc/service_callback_test.go b/internal/auth/oidc/service_callback_test.go index cd84e1d9a1..0b2374dc12 100644 --- a/internal/auth/oidc/service_callback_test.go +++ b/internal/auth/oidc/service_callback_test.go @@ -289,7 +289,7 @@ func Test_Callback(t *testing.T) { _, err := rw.Exec(ctx, "delete from auth_token", nil) require.NoError(err) // start with no users in the db - excludeUsers := []interface{}{"u_anon", "u_auth", "u_recovery"} + excludeUsers := []any{"u_anon", "u_auth", "u_recovery"} _, err = rw.Exec(ctx, "delete from iam_user where public_id not in(?, ?, ?)", excludeUsers) require.NoError(err) // start with no oplog entries @@ -316,7 +316,7 @@ func Test_Callback(t *testing.T) { } tp.SetExpectedSubject(tt.wantSubject) - info := map[string]interface{}{} + info := map[string]any{} if tt.wantSubject != "" { info["sub"] = tt.wantSubject } @@ -346,13 +346,13 @@ func Test_Callback(t *testing.T) { // make sure there are no tokens in the db.. var tokens []*authtoken.AuthToken - err := rw.SearchWhere(ctx, &tokens, "1=?", []interface{}{1}) + err := rw.SearchWhere(ctx, &tokens, "1=?", []any{1}) require.NoError(err) assert.Equal(0, len(tokens)) // make sure there weren't any oplog entries written. var entries []*oplog.Entry - err = rw.SearchWhere(ctx, &entries, "1=?", []interface{}{1}) + err = rw.SearchWhere(ctx, &entries, "1=?", []any{1}) require.NoError(err) amId := "" if tt.am != nil { @@ -366,7 +366,7 @@ func Test_Callback(t *testing.T) { // make sure a pending token was created. var tokens []*authtoken.AuthToken - err = rw.SearchWhere(ctx, &tokens, "1=?", []interface{}{1}) + err = rw.SearchWhere(ctx, &tokens, "1=?", []any{1}) require.NoError(err) require.Equal(1, len(tokens)) tk, err := atRepo.LookupAuthToken(ctx, tokens[0].PublicId) @@ -375,7 +375,7 @@ func Test_Callback(t *testing.T) { // make sure the account was updated properly var acct Account - err = rw.LookupWhere(ctx, &acct, "auth_method_id = ? and subject = ?", []interface{}{tt.am.PublicId, tt.wantSubject}) + err = rw.LookupWhere(ctx, &acct, "auth_method_id = ? and subject = ?", []any{tt.am.PublicId, tt.wantSubject}) require.NoError(err) assert.Equal(tt.wantInfoEmail, acct.Email) assert.Equal(tt.wantInfoName, acct.FullName) @@ -391,7 +391,7 @@ func Test_Callback(t *testing.T) { // check the oplog entries. var entries []*oplog.Entry - err = rw.SearchWhere(ctx, &entries, "1=?", []interface{}{1}) + err = rw.SearchWhere(ctx, &entries, "1=?", []any{1}) require.NoError(err) oplogWrapper, err := kmsCache.GetWrapper(ctx, tt.am.ScopeId, kms.KeyPurposeOplog) require.NoError(err) @@ -438,7 +438,7 @@ func Test_Callback(t *testing.T) { _, err := rw.Exec(ctx, "delete from auth_token", nil) require.NoError(err) // start with no users in the db - excludeUsers := []interface{}{"u_anon", "u_auth", "u_recovery"} + excludeUsers := []any{"u_anon", "u_auth", "u_recovery"} _, err = rw.Exec(ctx, "delete from iam_user where public_id not in(?, ?, ?)", excludeUsers) require.NoError(err) // start with no oplog entries @@ -456,7 +456,7 @@ func Test_Callback(t *testing.T) { wantSubject := "replay-attack-with-dup-state@example.com" tp.SetExpectedSubject(wantSubject) - tp.SetUserInfoReply(map[string]interface{}{"sub": wantSubject}) + tp.SetUserInfoReply(map[string]any{"sub": wantSubject}) tp.SetExpectedAuthNonce(testNonce) // the first request should succeed. @@ -500,7 +500,7 @@ func Test_StartAuth_to_Callback(t *testing.T) { _, err := rw.Exec(ctx, "delete from auth_token", nil) require.NoError(err) // start with no users in the db - excludeUsers := []interface{}{"u_anon", "u_auth", "u_recovery"} + excludeUsers := []any{"u_anon", "u_auth", "u_recovery"} _, err = rw.Exec(ctx, "delete from iam_user where public_id not in(?, ?, ?)", excludeUsers) require.NoError(err) // start with no oplog entries @@ -590,7 +590,7 @@ func Test_StartAuth_to_Callback(t *testing.T) { // check to make sure there's a pending token, after the successful callback var tokens []*authtoken.AuthToken - err = rw.SearchWhere(ctx, &tokens, "1=?", []interface{}{1}) + err = rw.SearchWhere(ctx, &tokens, "1=?", []any{1}) require.NoError(err) require.Equal(1, len(tokens)) tk, err := atRepo.LookupAuthToken(ctx, tokens[0].PublicId) @@ -680,7 +680,7 @@ func Test_ManagedGroupFiltering(t *testing.T) { tp.SetExpectedAuthCode(code) tp.SetExpectedSubject(sub) tp.SetCustomAudience("foo", "alice-rp") - info := map[string]interface{}{ + info := map[string]any{ "roles": []string{"user", "operator"}, "sub": "alice@example.com", "email": "alice-alias@example.com", diff --git a/internal/auth/oidc/signing_alg_test.go b/internal/auth/oidc/signing_alg_test.go index def7b31c3d..4dc22237bf 100644 --- a/internal/auth/oidc/signing_alg_test.go +++ b/internal/auth/oidc/signing_alg_test.go @@ -122,7 +122,7 @@ func TestSigningAlg_Create(t *testing.T) { assert.NoError(err) } found := AllocSigningAlg() - require.NoError(rw.LookupWhere(ctx, &found, "oidc_method_id = ? and signing_alg_name = ?", []interface{}{tt.args.authMethodId, string(tt.args.alg)})) + require.NoError(rw.LookupWhere(ctx, &found, "oidc_method_id = ? and signing_alg_name = ?", []any{tt.args.authMethodId, string(tt.args.alg)})) assert.Equal(got, &found) } }) @@ -209,7 +209,7 @@ func TestSigningAlg_Delete(t *testing.T) { } assert.Equal(tt.wantRowsDeleted, deletedRows) found := AllocSigningAlg() - err = rw.LookupWhere(ctx, &found, "oidc_method_id = ? and signing_alg_name = ?", []interface{}{tt.SigningAlg.OidcMethodId, tt.SigningAlg.String()}) + err = rw.LookupWhere(ctx, &found, "oidc_method_id = ? and signing_alg_name = ?", []any{tt.SigningAlg.OidcMethodId, tt.SigningAlg.String()}) assert.Truef(errors.IsNotFoundError(err), "unexpected error: %s", err.Error()) }) } diff --git a/internal/auth/oidc/testing.go b/internal/auth/oidc/testing.go index 75b4a919fb..dfe48836b5 100644 --- a/internal/auth/oidc/testing.go +++ b/internal/auth/oidc/testing.go @@ -65,7 +65,7 @@ func TestAuthMethod( require.NoError(err) if len(opts.withAudClaims) > 0 { - newAudClaims := make([]interface{}, 0, len(opts.withAudClaims)) + newAudClaims := make([]any, 0, len(opts.withAudClaims)) for _, a := range opts.withAudClaims { aud, err := NewAudClaim(ctx, authMethod.PublicId, a) require.NoError(err) @@ -76,7 +76,7 @@ func TestAuthMethod( require.Equal(len(opts.withAudClaims), len(authMethod.AudClaims)) } if len(opts.withCertificates) > 0 { - newCerts := make([]interface{}, 0, len(opts.withCertificates)) + newCerts := make([]any, 0, len(opts.withCertificates)) for _, c := range opts.withCertificates { pem, err := EncodeCertificates(ctx, c) require.NoError(err) @@ -89,7 +89,7 @@ func TestAuthMethod( require.Equal(len(opts.withCertificates), len(authMethod.Certificates)) } if len(opts.withSigningAlgs) > 0 { - newAlgs := make([]interface{}, 0, len(opts.withSigningAlgs)) + newAlgs := make([]any, 0, len(opts.withSigningAlgs)) for _, a := range opts.withSigningAlgs { alg, err := NewSigningAlg(ctx, authMethod.PublicId, a) require.NoError(err) @@ -100,7 +100,7 @@ func TestAuthMethod( require.Equal(len(opts.withSigningAlgs), len(authMethod.SigningAlgs)) } if len(opts.withClaimsScopes) > 0 { - newClaimsScopes := make([]interface{}, 0, len(opts.withClaimsScopes)) + newClaimsScopes := make([]any, 0, len(opts.withClaimsScopes)) for _, cs := range opts.withClaimsScopes { s, err := NewClaimsScope(ctx, authMethod.PublicId, cs) require.NoError(err) @@ -111,7 +111,7 @@ func TestAuthMethod( require.Equal(len(opts.withClaimsScopes), len(authMethod.ClaimsScopes)) } if len(opts.withAccountClaimMap) > 0 { - newAccountClaimMaps := make([]interface{}, 0, len(opts.withAccountClaimMap)) + newAccountClaimMaps := make([]any, 0, len(opts.withAccountClaimMap)) for k, v := range opts.withAccountClaimMap { acm, err := NewAccountClaimMap(ctx, authMethod.PublicId, k, v) require.NoError(err) diff --git a/internal/auth/password/argon2.go b/internal/auth/password/argon2.go index 64aad44fe3..5dbfd35f92 100644 --- a/internal/auth/password/argon2.go +++ b/internal/auth/password/argon2.go @@ -108,9 +108,9 @@ func (c *Argon2Configuration) oplog(op oplog.OpType) oplog.Metadata { return metadata } -func (c *Argon2Configuration) whereDup() (string, []interface{}) { +func (c *Argon2Configuration) whereDup() (string, []any) { var where []string - var args []interface{} + var args []any where, args = append(where, "password_method_id = ?"), append(args, c.PasswordMethodId) where, args = append(where, "iterations = ?"), append(args, c.Iterations) diff --git a/internal/auth/password/argon2_test.go b/internal/auth/password/argon2_test.go index f53fb4534e..362f3d1300 100644 --- a/internal/auth/password/argon2_test.go +++ b/internal/auth/password/argon2_test.go @@ -26,7 +26,7 @@ func TestArgon2Configuration_New(t *testing.T) { t.Run("default-configuration", func(t *testing.T) { assert, require := assert.New(t), require.New(t) var confs []*Argon2Configuration - err := rw.SearchWhere(ctx, &confs, "password_method_id = ?", []interface{}{authMethodId}) + err := rw.SearchWhere(ctx, &confs, "password_method_id = ?", []any{authMethodId}) require.NoError(err) require.Equal(1, len(confs)) got := confs[0] @@ -59,7 +59,7 @@ func TestArgon2Configuration_New(t *testing.T) { assert, require := assert.New(t), require.New(t) var confs []*Argon2Configuration - err := rw.SearchWhere(ctx, &confs, "password_method_id = ?", []interface{}{authMethodId}) + err := rw.SearchWhere(ctx, &confs, "password_method_id = ?", []any{authMethodId}) require.NoError(err) assert.Equal(1, len(confs)) @@ -85,7 +85,7 @@ func TestArgon2Configuration_New(t *testing.T) { assert.NoError(err) confs = nil - err = rw.SearchWhere(ctx, &confs, "password_method_id = ?", []interface{}{authMethodId}) + err = rw.SearchWhere(ctx, &confs, "password_method_id = ?", []any{authMethodId}) require.NoError(err) assert.Equal(3, len(confs)) }) @@ -143,7 +143,7 @@ func TestArgon2Configuration_Readonly(t *testing.T) { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) var confs []*Argon2Configuration - err := rw.SearchWhere(context.Background(), &confs, "password_method_id = ?", []interface{}{authMethodId}) + err := rw.SearchWhere(context.Background(), &confs, "password_method_id = ?", []any{authMethodId}) require.NoError(err) assert.Greater(len(confs), 0) orig := confs[0] @@ -293,7 +293,7 @@ func testArgon2Confs(t *testing.T, conn *db.DB, authMethodId string, count int) assert, require := assert.New(t), require.New(t) rw := db.New(conn) var confs []*Argon2Configuration - err := rw.SearchWhere(context.Background(), &confs, "password_method_id = ?", []interface{}{authMethodId}) + err := rw.SearchWhere(context.Background(), &confs, "password_method_id = ?", []any{authMethodId}) require.NoError(err) assert.Equal(1, len(confs)) base := confs[0] diff --git a/internal/auth/password/repository_account.go b/internal/auth/password/repository_account.go index 5e5c7f7cc3..005a6b9da7 100644 --- a/internal/auth/password/repository_account.go +++ b/internal/auth/password/repository_account.go @@ -155,7 +155,7 @@ func (r *Repository) ListAccounts(ctx context.Context, withAuthMethodId string, limit = opts.withLimit } var accts []*Account - err := r.reader.SearchWhere(ctx, &accts, "auth_method_id = ?", []interface{}{withAuthMethodId}, db.WithLimit(limit)) + err := r.reader.SearchWhere(ctx, &accts, "auth_method_id = ?", []any{withAuthMethodId}, db.WithLimit(limit)) if err != nil { return nil, errors.Wrap(ctx, err, op) } @@ -263,7 +263,7 @@ func (r *Repository) UpdateAccount(ctx context.Context, scopeId string, a *Accou } var dbMask, nullFields []string dbMask, nullFields = dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ "Name": a.Name, "Description": a.Description, "LoginName": a.LoginName, diff --git a/internal/auth/password/repository_authmethod.go b/internal/auth/password/repository_authmethod.go index 1bf617758d..a7ec25f1b3 100644 --- a/internal/auth/password/repository_authmethod.go +++ b/internal/auth/password/repository_authmethod.go @@ -199,7 +199,7 @@ func (r *Repository) UpdateAuthMethod(ctx context.Context, authMethod *AuthMetho } var dbMask, nullFields []string dbMask, nullFields = dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ "Name": authMethod.Name, "Description": authMethod.Description, "MinPasswordLength": authMethod.MinPasswordLength, @@ -323,7 +323,7 @@ func (r *Repository) getAuthMethods(ctx context.Context, authMethodId string, sc } } - var args []interface{} + var args []any var where []string switch { case authMethodId != "": diff --git a/internal/auth/password/repository_configuration.go b/internal/auth/password/repository_configuration.go index dcd1ebda4b..f4054a8e09 100644 --- a/internal/auth/password/repository_configuration.go +++ b/internal/auth/password/repository_configuration.go @@ -134,7 +134,7 @@ func (c *currentConfig) TableName() string { func (r *Repository) currentConfig(ctx context.Context, authMethodId string) (*currentConfig, error) { const op = "password.(Repository).currentConfig" var cc currentConfig - if err := r.reader.LookupWhere(ctx, &cc, "password_method_id = ?", []interface{}{authMethodId}); err != nil { + if err := r.reader.LookupWhere(ctx, &cc, "password_method_id = ?", []any{authMethodId}); err != nil { return nil, errors.Wrap(ctx, err, op) } return &cc, nil @@ -144,7 +144,7 @@ func (r *Repository) currentConfigForAccount(ctx context.Context, accountId stri const op = "password.(Repository).currentConfigForAccount" var confs []currentConfig - rows, err := r.reader.Query(ctx, currentConfigForAccountQuery, []interface{}{sql.Named("public_id", accountId)}) + rows, err := r.reader.Query(ctx, currentConfigForAccountQuery, []any{sql.Named("public_id", accountId)}) if err != nil { return nil, errors.Wrap(ctx, err, op) } diff --git a/internal/auth/password/repository_password.go b/internal/auth/password/repository_password.go index 655cb61722..3a0e943b89 100644 --- a/internal/auth/password/repository_password.go +++ b/internal/auth/password/repository_password.go @@ -214,7 +214,7 @@ func (r *Repository) authenticate(ctx context.Context, scopeId, authMethodId, lo const op = "password.(Repository).authenticate" var accts []authAccount - rows, err := r.reader.Query(ctx, authenticateQuery, []interface{}{sql.Named("auth_method_id", authMethodId), sql.Named("login_name", loginName)}) + rows, err := r.reader.Query(ctx, authenticateQuery, []any{sql.Named("auth_method_id", authMethodId), sql.Named("login_name", loginName)}) if err != nil { return nil, errors.Wrap(ctx, err, op) } @@ -316,7 +316,7 @@ func (r *Repository) SetPassword(ctx context.Context, scopeId, accountId, passwo acct = updatedAccount oldCred := allocCredential() - if err := rr.LookupWhere(ctx, &oldCred, "password_account_id = ?", []interface{}{accountId}); err != nil { + if err := rr.LookupWhere(ctx, &oldCred, "password_account_id = ?", []any{accountId}); err != nil { if !errors.IsNotFoundError(err) { return errors.Wrap(ctx, err, op) } diff --git a/internal/auth/password/repository_password_test.go b/internal/auth/password/repository_password_test.go index 6fed14c7fd..567a2dc98f 100644 --- a/internal/auth/password/repository_password_test.go +++ b/internal/auth/password/repository_password_test.go @@ -171,7 +171,7 @@ func TestRepository_AuthenticateRehash(t *testing.T) { // Get the credential for the new account and verify the KDF used the // original argon2 configuration origCred := &Argon2Credential{Argon2Credential: &store.Argon2Credential{}} - require.NoError(rw.LookupWhere(ctx, origCred, "password_account_id = ?", []interface{}{origAcct.PublicId})) + require.NoError(rw.LookupWhere(ctx, origCred, "password_account_id = ?", []any{origAcct.PublicId})) assert.Equal(origAcct.PublicId, origCred.PasswordAccountId) assert.Equal(origConfId, origCred.PasswordConfId) assert.Equal(origCred.CreateTime, origCred.UpdateTime, "create and update times are equal") diff --git a/internal/authtoken/repository.go b/internal/authtoken/repository.go index 6f59dd416c..e4b85c1d32 100644 --- a/internal/authtoken/repository.go +++ b/internal/authtoken/repository.go @@ -299,7 +299,7 @@ func (r *Repository) ListAuthTokens(ctx context.Context, withScopeIds []string, // use the view, to bring in the required account columns. Just don't forget // to convert them before returning them var atvs []*authTokenView - if err := r.reader.SearchWhere(ctx, &atvs, "auth_account_id in (select public_id from auth_account where scope_id in (?))", []interface{}{withScopeIds}, db.WithLimit(opts.withLimit)); err != nil { + if err := r.reader.SearchWhere(ctx, &atvs, "auth_account_id in (select public_id from auth_account where scope_id in (?))", []any{withScopeIds}, db.WithLimit(opts.withLimit)); err != nil { return nil, errors.Wrap(ctx, err, op) } authTokens := make([]*AuthToken, 0, len(atvs)) @@ -422,7 +422,7 @@ func (r *Repository) IssueAuthToken(ctx context.Context, tokenRequestId string) func (r *Repository) CloseExpiredPendingTokens(ctx context.Context) (int, error) { const op = "authtoken.(Repository).CloseExpiredPendingTokens" - args := []interface{}{string(FailedStatus), string(PendingStatus)} + args := []any{string(FailedStatus), string(PendingStatus)} const sql = `update auth_token set status = ? where status = ? and now() > expiration_time` var tokensClosed int _, err := r.writer.DoTx( diff --git a/internal/cmd/base/dev.go b/internal/cmd/base/dev.go index f8578e1d68..90d702ad09 100644 --- a/internal/cmd/base/dev.go +++ b/internal/cmd/base/dev.go @@ -270,7 +270,7 @@ func (b *Server) CreateDevOidcAuthMethod(ctx context.Context) error { subInfo := map[string]*capoidc.TestSubject{ b.DevLoginName: { Password: b.DevPassword, - UserInfo: map[string]interface{}{ + UserInfo: map[string]any{ "email": "admin@localhost", "name": "Admin User", }, @@ -279,7 +279,7 @@ func (b *Server) CreateDevOidcAuthMethod(ctx context.Context) error { if b.DevOidcSetup.createUnpriv { subInfo[b.DevUnprivilegedLoginName] = &capoidc.TestSubject{ Password: b.DevUnprivilegedPassword, - UserInfo: map[string]interface{}{ + UserInfo: map[string]any{ "email": "user@localhost", "name": "Unprivileged User", }, @@ -294,7 +294,7 @@ func (b *Server) CreateDevOidcAuthMethod(ctx context.Context) error { capoidc.WithTestHost(b.DevOidcSetup.hostAddr), capoidc.WithTestPort(b.DevOidcSetup.oidcPort), capoidc.WithTestDefaults(&capoidc.TestProviderDefaults{ - CustomClaims: map[string]interface{}{ + CustomClaims: map[string]any{ "mode": "dev", }, SubjectInfo: subInfo, @@ -437,12 +437,12 @@ type oidcLogger struct { } // Errorf will use the sys eventer to emit an error event -func (l *oidcLogger) Errorf(format string, args ...interface{}) { +func (l *oidcLogger) Errorf(format string, args ...any) { event.WriteError(l.Ctx, l.caller(), fmt.Errorf(format, args...)) } // Infof will use the sys eventer to emit an system event -func (l *oidcLogger) Infof(format string, args ...interface{}) { +func (l *oidcLogger) Infof(format string, args ...any) { event.WriteSysEvent(l.Ctx, l.caller(), fmt.Sprintf(format, args...)) } diff --git a/internal/cmd/base/dev_test.go b/internal/cmd/base/dev_test.go index 805a7a97de..2a184d4e6c 100644 --- a/internal/cmd/base/dev_test.go +++ b/internal/cmd/base/dev_test.go @@ -30,7 +30,7 @@ func Test_oidcLogger_Errorf(t *testing.T) { tests := []struct { name string fmt string - args []interface{} + args []any }{ { name: "no-args", @@ -39,7 +39,7 @@ func Test_oidcLogger_Errorf(t *testing.T) { { name: "with-args", fmt: "%s: simple", - args: []interface{}{"error"}, + args: []any{"error"}, }, } for _, tt := range tests { @@ -54,9 +54,9 @@ func Test_oidcLogger_Errorf(t *testing.T) { gotEvent := &cloudevents.Event{} err = json.Unmarshal(b, gotEvent) require.NoErrorf(err, "json: %s", string(b)) - expected := gotEvent.Data.(map[string]interface{}) + expected := gotEvent.Data.(map[string]any) expected["error"] = fmt.Sprintf(tt.fmt, tt.args...) - assert.Equal(expected, gotEvent.Data.(map[string]interface{})) + assert.Equal(expected, gotEvent.Data.(map[string]any)) }) } } @@ -76,7 +76,7 @@ func Test_oidcLogger_Infof(t *testing.T) { tests := []struct { name string fmt string - args []interface{} + args []any }{ { name: "no-args", @@ -85,7 +85,7 @@ func Test_oidcLogger_Infof(t *testing.T) { { name: "with-args", fmt: "%s: simple", - args: []interface{}{"info"}, + args: []any{"info"}, }, } for _, tt := range tests { @@ -100,9 +100,9 @@ func Test_oidcLogger_Infof(t *testing.T) { gotEvent := &cloudevents.Event{} err = json.Unmarshal(b, gotEvent) require.NoErrorf(err, "json: %s", string(b)) - expected := gotEvent.Data.(map[string]interface{}) + expected := gotEvent.Data.(map[string]any) expected["msg"] = fmt.Sprintf(tt.fmt, tt.args...) - assert.Equal(expected, gotEvent.Data.(map[string]interface{})) + assert.Equal(expected, gotEvent.Data.(map[string]any)) }) } } diff --git a/internal/cmd/base/flags.go b/internal/cmd/base/flags.go index 9ee7dad520..b864518a67 100644 --- a/internal/cmd/base/flags.go +++ b/internal/cmd/base/flags.go @@ -88,7 +88,7 @@ func (b *boolValue) Set(s string) error { return nil } -func (b *boolValue) Get() interface{} { return *b.target } +func (b *boolValue) Get() any { return *b.target } func (b *boolValue) String() string { return strconv.FormatBool(*b.target) } func (b *boolValue) Example() string { return "" } func (b *boolValue) Hidden() bool { return b.hidden } @@ -153,10 +153,10 @@ func (i *intValue) Set(s string) error { return nil } -func (i *intValue) Get() interface{} { return int(*i.target) } -func (i *intValue) String() string { return strconv.Itoa(int(*i.target)) } -func (i *intValue) Example() string { return "int" } -func (i *intValue) Hidden() bool { return i.hidden } +func (i *intValue) Get() any { return int(*i.target) } +func (i *intValue) String() string { return strconv.Itoa(int(*i.target)) } +func (i *intValue) Example() string { return "int" } +func (i *intValue) Hidden() bool { return i.hidden } // -- Int64Var and int64Value type Int64Var struct { @@ -217,10 +217,10 @@ func (i *int64Value) Set(s string) error { return nil } -func (i *int64Value) Get() interface{} { return int64(*i.target) } -func (i *int64Value) String() string { return strconv.FormatInt(int64(*i.target), 10) } -func (i *int64Value) Example() string { return "int" } -func (i *int64Value) Hidden() bool { return i.hidden } +func (i *int64Value) Get() any { return int64(*i.target) } +func (i *int64Value) String() string { return strconv.FormatInt(int64(*i.target), 10) } +func (i *int64Value) Example() string { return "int" } +func (i *int64Value) Hidden() bool { return i.hidden } // -- UintVar && uintValue type UintVar struct { @@ -281,10 +281,10 @@ func (i *uintValue) Set(s string) error { return nil } -func (i *uintValue) Get() interface{} { return uint(*i.target) } -func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i.target), 10) } -func (i *uintValue) Example() string { return "uint" } -func (i *uintValue) Hidden() bool { return i.hidden } +func (i *uintValue) Get() any { return uint(*i.target) } +func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i.target), 10) } +func (i *uintValue) Example() string { return "uint" } +func (i *uintValue) Hidden() bool { return i.hidden } // -- Uint64Var and uint64Value type Uint64Var struct { @@ -345,10 +345,10 @@ func (i *uint64Value) Set(s string) error { return nil } -func (i *uint64Value) Get() interface{} { return uint64(*i.target) } -func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i.target), 10) } -func (i *uint64Value) Example() string { return "uint" } -func (i *uint64Value) Hidden() bool { return i.hidden } +func (i *uint64Value) Get() any { return uint64(*i.target) } +func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i.target), 10) } +func (i *uint64Value) Example() string { return "uint" } +func (i *uint64Value) Hidden() bool { return i.hidden } // -- StringVar and stringValue type StringVar struct { @@ -402,10 +402,10 @@ func (s *stringValue) Set(val string) error { return nil } -func (s *stringValue) Get() interface{} { return *s.target } -func (s *stringValue) String() string { return *s.target } -func (s *stringValue) Example() string { return "string" } -func (s *stringValue) Hidden() bool { return s.hidden } +func (s *stringValue) Get() any { return *s.target } +func (s *stringValue) String() string { return *s.target } +func (s *stringValue) Example() string { return "string" } +func (s *stringValue) Hidden() bool { return s.hidden } // -- Float64Var and float64Value type Float64Var struct { @@ -466,10 +466,10 @@ func (f *float64Value) Set(s string) error { return nil } -func (f *float64Value) Get() interface{} { return float64(*f.target) } -func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f.target), 'g', -1, 64) } -func (f *float64Value) Example() string { return "float" } -func (f *float64Value) Hidden() bool { return f.hidden } +func (f *float64Value) Get() any { return float64(*f.target) } +func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f.target), 'g', -1, 64) } +func (f *float64Value) Example() string { return "float" } +func (f *float64Value) Hidden() bool { return f.hidden } // -- DurationVar and durationValue type DurationVar struct { @@ -534,10 +534,10 @@ func (d *durationValue) Set(s string) error { return nil } -func (d *durationValue) Get() interface{} { return time.Duration(*d.target) } -func (d *durationValue) String() string { return (*d.target).String() } -func (d *durationValue) Example() string { return "duration" } -func (d *durationValue) Hidden() bool { return d.hidden } +func (d *durationValue) Get() any { return time.Duration(*d.target) } +func (d *durationValue) String() string { return (*d.target).String() } +func (d *durationValue) Example() string { return "duration" } +func (d *durationValue) Hidden() bool { return d.hidden } // appendDurationSuffix is used as a backwards-compat tool for assuming users // meant "seconds" when they do not provide a suffixed duration value. @@ -637,10 +637,10 @@ func (s *stringSliceValue) Set(val string) error { return nil } -func (s *stringSliceValue) Get() interface{} { return *s.target } -func (s *stringSliceValue) String() string { return strings.Join(*s.target, ",") } -func (s *stringSliceValue) Example() string { return "string" } -func (s *stringSliceValue) Hidden() bool { return s.hidden } +func (s *stringSliceValue) Get() any { return *s.target } +func (s *stringSliceValue) String() string { return strings.Join(*s.target, ",") } +func (s *stringSliceValue) Example() string { return "string" } +func (s *stringSliceValue) Hidden() bool { return s.hidden } // -- StringMapVar and stringMapValue type StringMapVar struct { @@ -697,10 +697,10 @@ func (s *stringMapValue) Set(val string) error { return nil } -func (s *stringMapValue) Get() interface{} { return *s.target } -func (s *stringMapValue) String() string { return mapToKV(*s.target) } -func (s *stringMapValue) Example() string { return "key=value" } -func (s *stringMapValue) Hidden() bool { return s.hidden } +func (s *stringMapValue) Get() any { return *s.target } +func (s *stringMapValue) String() string { return mapToKV(*s.target) } +func (s *stringMapValue) Example() string { return "key=value" } +func (s *stringMapValue) Hidden() bool { return s.hidden } func mapToKV(m map[string]string) string { list := make([]string, 0, len(m)) @@ -826,10 +826,10 @@ func sliceMapToKV(m map[string][]string) string { return strings.Join(list, ", ") } -func (c *stringSliceMapValue) Get() interface{} { return *c.target } -func (c *stringSliceMapValue) String() string { return sliceMapToKV(*c.target) } -func (c *stringSliceMapValue) Example() string { return "key1=val-a, key2=val-b,val-c" } -func (c *stringSliceMapValue) Hidden() bool { return c.hidden } +func (c *stringSliceMapValue) Get() any { return *c.target } +func (c *stringSliceMapValue) String() string { return sliceMapToKV(*c.target) } +func (c *stringSliceMapValue) Example() string { return "key1=val-a, key2=val-b,val-c" } +func (c *stringSliceMapValue) Hidden() bool { return c.hidden } // -- VarFlag type VarFlag struct { @@ -1011,7 +1011,7 @@ func (c *combinedSliceValue) Set(val string) error { return nil } -func (c *combinedSliceValue) Get() interface{} { return *c.target } -func (c *combinedSliceValue) String() string { return pretty.Sprint(*c.target) } -func (c *combinedSliceValue) Example() string { return "" } -func (c *combinedSliceValue) Hidden() bool { return c.hidden } +func (c *combinedSliceValue) Get() any { return *c.target } +func (c *combinedSliceValue) String() string { return pretty.Sprint(*c.target) } +func (c *combinedSliceValue) Example() string { return "" } +func (c *combinedSliceValue) Hidden() bool { return c.hidden } diff --git a/internal/cmd/base/format.go b/internal/cmd/base/format.go index 89579b06b9..a72b3ec038 100644 --- a/internal/cmd/base/format.go +++ b/internal/cmd/base/format.go @@ -24,7 +24,7 @@ func ScopeInfoForOutput(scp *scopes.ScopeInfo, maxLength int) string { if scp == nil { return " " } - vals := map[string]interface{}{ + vals := map[string]any{ "ID": scp.Id, "Type": scp.Type, "Name": scp.Name, @@ -39,14 +39,14 @@ func PluginInfoForOutput(plg *plugins.PluginInfo, maxLength int) string { if plg == nil { return " " } - vals := map[string]interface{}{ + vals := map[string]any{ "ID": plg.Id, "Name": plg.Name, } return WrapMap(4, maxLength, vals) } -func MaxAttributesLength(nonAttributesMap, attributesMap map[string]interface{}, keySubstMap map[string]string) int { +func MaxAttributesLength(nonAttributesMap, attributesMap map[string]any, keySubstMap map[string]string) int { // We always print a scope ID and in some cases this particular key ends up // being the longest key, so start with it as a baseline. It's always // indented by 2 in addition to the normal offset so take that into account. @@ -116,7 +116,7 @@ func WrapSlice(prefixSpaces int, input []string) string { return strings.Join(ret, "\n") } -func WrapMap(prefixSpaces, maxLengthOverride int, input map[string]interface{}) string { +func WrapMap(prefixSpaces, maxLengthOverride int, input map[string]any) string { maxKeyLength := maxLengthOverride if maxKeyLength == 0 { for k := range input { @@ -150,7 +150,7 @@ func WrapMap(prefixSpaces, maxLengthOverride int, input map[string]interface{}) vOut := fmt.Sprintf("%v", v) switch v.(type) { - case map[string]interface{}: + case map[string]any: buf, err := json.MarshalIndent(v, strings.Repeat(" ", prefixSpaces), " ") if err != nil { vOut = "[Unable to Print]" @@ -194,7 +194,7 @@ func (c *Command) PrintApiError(in *api.Error, contextStr string, opt ...Option) c.UI.Error(string(b)) default: - nonAttributeMap := map[string]interface{}{ + nonAttributeMap := map[string]any{ "Status": in.Response().StatusCode(), "Kind": in.Kind, "Message": in.Message, @@ -346,7 +346,7 @@ func (c *Command) PrintJsonItems(resp *api.Response) bool { // An output formatter for json output of an object type JsonFormatter struct{} -func (j JsonFormatter) Format(data interface{}) ([]byte, error) { +func (j JsonFormatter) Format(data any) ([]byte, error) { return json.Marshal(data) } diff --git a/internal/cmd/base/logging.go b/internal/cmd/base/logging.go index 468f3fd8d7..59cfe81c68 100644 --- a/internal/cmd/base/logging.go +++ b/internal/cmd/base/logging.go @@ -61,34 +61,34 @@ type GRPCLogFaker struct { Log bool } -func (g *GRPCLogFaker) Fatal(args ...interface{}) { +func (g *GRPCLogFaker) Fatal(args ...any) { g.Logger.Error(fmt.Sprint(args...)) os.Exit(1) } -func (g *GRPCLogFaker) Fatalf(format string, args ...interface{}) { +func (g *GRPCLogFaker) Fatalf(format string, args ...any) { g.Logger.Error(fmt.Sprintf(format, args...)) os.Exit(1) } -func (g *GRPCLogFaker) Fatalln(args ...interface{}) { +func (g *GRPCLogFaker) Fatalln(args ...any) { g.Logger.Error(fmt.Sprintln(args...)) os.Exit(1) } -func (g *GRPCLogFaker) Print(args ...interface{}) { +func (g *GRPCLogFaker) Print(args ...any) { if g.Log && g.Logger.IsDebug() { g.Logger.Debug(fmt.Sprint(args...)) } } -func (g *GRPCLogFaker) Printf(format string, args ...interface{}) { +func (g *GRPCLogFaker) Printf(format string, args ...any) { if g.Log && g.Logger.IsDebug() { g.Logger.Debug(fmt.Sprintf(format, args...)) } } -func (g *GRPCLogFaker) Println(args ...interface{}) { +func (g *GRPCLogFaker) Println(args ...any) { if g.Log && g.Logger.IsDebug() { g.Logger.Debug(fmt.Sprintln(args...)) } diff --git a/internal/cmd/commands/accountscmd/funcs.go b/internal/cmd/commands/accountscmd/funcs.go index d2bada13d1..2a0fcb922f 100644 --- a/internal/cmd/commands/accountscmd/funcs.go +++ b/internal/cmd/commands/accountscmd/funcs.go @@ -296,7 +296,7 @@ func (c *Command) printListTable(items []*accounts.Account) string { } func printItemTable(item *accounts.Account, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if item.Id != "" { nonAttributeMap["ID"] = item.Id } diff --git a/internal/cmd/commands/authenticate/oidc.go b/internal/cmd/commands/authenticate/oidc.go index 1def6aa2ce..c94e66706b 100644 --- a/internal/cmd/commands/authenticate/oidc.go +++ b/internal/cmd/commands/authenticate/oidc.go @@ -130,7 +130,7 @@ func (c *OidcCommand) Run(args []string) int { return case <-time.After(1500 * time.Millisecond): - result, err = aClient.Authenticate(c.Context, c.FlagAuthMethodId, "token", map[string]interface{}{ + result, err = aClient.Authenticate(c.Context, c.FlagAuthMethodId, "token", map[string]any{ "token_id": startResp.TokenId, }) if err != nil { diff --git a/internal/cmd/commands/authenticate/password.go b/internal/cmd/commands/authenticate/password.go index b0dc40634a..988d062019 100644 --- a/internal/cmd/commands/authenticate/password.go +++ b/internal/cmd/commands/authenticate/password.go @@ -142,7 +142,7 @@ func (c *PasswordCommand) Run(args []string) int { aClient := authmethods.NewClient(client) result, err := aClient.Authenticate(c.Context, c.FlagAuthMethodId, "login", - map[string]interface{}{ + map[string]any{ "login_name": c.flagLoginName, "password": c.flagPassword, }) diff --git a/internal/cmd/commands/authmethodscmd/funcs.go b/internal/cmd/commands/authmethodscmd/funcs.go index 8cfdf9cb26..8ffc53084f 100644 --- a/internal/cmd/commands/authmethodscmd/funcs.go +++ b/internal/cmd/commands/authmethodscmd/funcs.go @@ -134,7 +134,7 @@ func (c *Command) printListTable(items []*authmethods.AuthMethod) string { } func printItemTable(item *authmethods.AuthMethod, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if item.Id != "" { nonAttributeMap["ID"] = item.Id } diff --git a/internal/cmd/commands/authmethodscmd/password_funcs.go b/internal/cmd/commands/authmethodscmd/password_funcs.go index 1f3b7a916d..a775c3de44 100644 --- a/internal/cmd/commands/authmethodscmd/password_funcs.go +++ b/internal/cmd/commands/authmethodscmd/password_funcs.go @@ -76,10 +76,10 @@ func extraPasswordFlagsFuncImpl(c *PasswordCommand, set *base.FlagSets, f *base. } func extraPasswordFlagHandlingFuncImpl(c *PasswordCommand, _ *base.FlagSets, opts *[]authmethods.Option) bool { - var attributes map[string]interface{} - addAttribute := func(name string, value interface{}) { + var attributes map[string]any + addAttribute := func(name string, value any) { if attributes == nil { - attributes = make(map[string]interface{}) + attributes = make(map[string]any) } attributes[name] = value } diff --git a/internal/cmd/commands/authtokenscmd/funcs.go b/internal/cmd/commands/authtokenscmd/funcs.go index a3caba2d8f..f3a469a704 100644 --- a/internal/cmd/commands/authtokenscmd/funcs.go +++ b/internal/cmd/commands/authtokenscmd/funcs.go @@ -122,7 +122,7 @@ func (c *Command) printListTable(items []*authtokens.AuthToken) string { } func printItemTable(item *authtokens.AuthToken, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{ + nonAttributeMap := map[string]any{ "ID": item.Id, "Auth Method ID": item.AuthMethodId, "User ID": item.UserId, diff --git a/internal/cmd/commands/connect/credentials_test.go b/internal/cmd/commands/connect/credentials_test.go index 91f749b865..2b4aa41f2a 100644 --- a/internal/cmd/commands/connect/credentials_test.go +++ b/internal/cmd/commands/connect/credentials_test.go @@ -14,7 +14,7 @@ var ( CredentialSource: &targets.CredentialSource{ CredentialType: string(credential.UsernamePasswordType), }, - Credential: map[string]interface{}{ + Credential: map[string]any{ "username": "user", "password": "pass", }, @@ -24,7 +24,7 @@ var ( CredentialSource: &targets.CredentialSource{ CredentialType: string(credential.SshPrivateKeyType), }, - Credential: map[string]interface{}{ + Credential: map[string]any{ "username": "user", "private_key": "my-pk", }, @@ -35,7 +35,7 @@ var ( Type: "vault", }, Secret: &targets.SessionSecret{ - Decoded: map[string]interface{}{ + Decoded: map[string]any{ "username": "vault-decoded-user", "password": "vault-decoded-pass", }, @@ -47,7 +47,7 @@ var ( Type: "vault", }, Secret: &targets.SessionSecret{ - Decoded: map[string]interface{}{ + Decoded: map[string]any{ "username": "vault-decoded-user", "private_key": "vault-decoded-pk", }, @@ -59,7 +59,7 @@ var ( Type: "static", }, Secret: &targets.SessionSecret{ - Decoded: map[string]interface{}{ + Decoded: map[string]any{ "username": "static-decoded-user", "password": "static-decoded-pass", }, @@ -71,7 +71,7 @@ var ( Type: "static", }, Secret: &targets.SessionSecret{ - Decoded: map[string]interface{}{ + Decoded: map[string]any{ "username": "static-decoded-user", "private_key": "static-decoded-pk", }, @@ -88,8 +88,8 @@ var ( Id: "credjson_id", }, Secret: &targets.SessionSecret{ - Decoded: map[string]interface{}{ - "secret": map[string]interface{}{ + Decoded: map[string]any{ + "secret": map[string]any{ "username": "password", }, }, @@ -101,7 +101,7 @@ var ( Type: "static", }, Secret: &targets.SessionSecret{ - Decoded: map[string]interface{}{ + Decoded: map[string]any{ "username": "decoded-user", "some-value": "decoded-some-value", }, @@ -113,7 +113,7 @@ var ( Type: "static", }, Secret: &targets.SessionSecret{ - Decoded: map[string]interface{}{ + Decoded: map[string]any{ "username": "decoded-user", "some-value1": "decoded-some-value1", }, @@ -137,7 +137,7 @@ func Test_parseCredentials(t *testing.T) { creds: []*targets.SessionCredential{ { Secret: &targets.SessionSecret{ - Decoded: map[string]interface{}{ + Decoded: map[string]any{ "username": "decoded-user", "private_key": "decoded-pk", }, diff --git a/internal/cmd/commands/connect/funcs.go b/internal/cmd/commands/connect/funcs.go index 555d1bf03b..eda4629566 100644 --- a/internal/cmd/commands/connect/funcs.go +++ b/internal/cmd/commands/connect/funcs.go @@ -13,7 +13,7 @@ import ( ) func generateSessionInfoTableOutput(in SessionInfo) string { - nonAttributeMap := map[string]interface{}{ + nonAttributeMap := map[string]any{ "Session ID": in.SessionId, "Protocol": in.Protocol, "Address": in.Address, @@ -52,7 +52,7 @@ func generateCredentialTableOutputSlice(prefixIndent int, creds []*targets.Sessi ret = append(ret, fmt.Sprintf("%sCredentials:", prefixString)) } for _, crd := range creds { - credMap := map[string]interface{}{ + credMap := map[string]any{ "Credential Store ID": crd.CredentialSource.CredentialStoreId, "Credential Source ID": crd.CredentialSource.Id, "Credential Store Type": crd.CredentialSource.Type, @@ -114,7 +114,7 @@ func fmtSecretForTable(indent int, sc *targets.SessionCredential) []string { func generateConnectionInfoTableOutput(in ConnectionInfo) string { var ret []string - nonAttributeMap := map[string]interface{}{ + nonAttributeMap := map[string]any{ "Connections Left": in.ConnectionsLeft, } @@ -138,7 +138,7 @@ func generateConnectionInfoTableOutput(in ConnectionInfo) string { func generateTerminationInfoTableOutput(in TerminationInfo) string { var ret []string - nonAttributeMap := map[string]interface{}{ + nonAttributeMap := map[string]any{ "Reason": in.Reason, } diff --git a/internal/cmd/commands/credentiallibrariescmd/funcs.go b/internal/cmd/commands/credentiallibrariescmd/funcs.go index cb78765442..e6a3efa1b0 100644 --- a/internal/cmd/commands/credentiallibrariescmd/funcs.go +++ b/internal/cmd/commands/credentiallibrariescmd/funcs.go @@ -114,7 +114,7 @@ func (c *Command) printListTable(items []*credentiallibraries.CredentialLibrary) } func printItemTable(item *credentiallibraries.CredentialLibrary, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if item.Id != "" { nonAttributeMap["ID"] = item.Id } diff --git a/internal/cmd/commands/credentiallibrariescmd/vault_funcs.go b/internal/cmd/commands/credentiallibrariescmd/vault_funcs.go index 6648c3cc01..9831fa7f9c 100644 --- a/internal/cmd/commands/credentiallibrariescmd/vault_funcs.go +++ b/internal/cmd/commands/credentiallibrariescmd/vault_funcs.go @@ -124,7 +124,7 @@ func extraVaultFlagHandlingFuncImpl(c *VaultCommand, _ *base.FlagSets, opts *[]c } fallthrough default: - mappings := make(map[string]interface{}, len(c.flagCredentialMapping)) + mappings := make(map[string]any, len(c.flagCredentialMapping)) for _, mapping := range c.flagCredentialMapping { switch { case len(mapping.Keys) != 1 || mapping.Keys[0] == "" || mapping.Value == "": diff --git a/internal/cmd/commands/credentialscmd/funcs.go b/internal/cmd/commands/credentialscmd/funcs.go index 65856a328f..e415739213 100644 --- a/internal/cmd/commands/credentialscmd/funcs.go +++ b/internal/cmd/commands/credentialscmd/funcs.go @@ -117,7 +117,7 @@ func (c *Command) printListTable(items []*credentials.Credential) string { } func printItemTable(item *credentials.Credential, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if item.Id != "" { nonAttributeMap["ID"] = item.Id } diff --git a/internal/cmd/commands/credentialstorescmd/funcs.go b/internal/cmd/commands/credentialstorescmd/funcs.go index 450066c0df..7bde10c393 100644 --- a/internal/cmd/commands/credentialstorescmd/funcs.go +++ b/internal/cmd/commands/credentialstorescmd/funcs.go @@ -123,7 +123,7 @@ func (c *Command) printListTable(items []*credentialstores.CredentialStore) stri } func printItemTable(item *credentialstores.CredentialStore, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if item.Id != "" { nonAttributeMap["ID"] = item.Id } diff --git a/internal/cmd/commands/database/funcs.go b/internal/cmd/commands/database/funcs.go index 8d8a2c1a19..a3ee92c8e9 100644 --- a/internal/cmd/commands/database/funcs.go +++ b/internal/cmd/commands/database/funcs.go @@ -105,7 +105,7 @@ type RoleInfo struct { } func generateInitialRoleTableOutput(in *RoleInfo) string { - nonAttributeMap := map[string]interface{}{ + nonAttributeMap := map[string]any{ "Role ID": in.RoleId, "Name": in.Name, } @@ -137,7 +137,7 @@ type AuthInfo struct { } func generateInitialAuthTableOutput(in *AuthInfo) string { - nonAttributeMap := map[string]interface{}{ + nonAttributeMap := map[string]any{ "Scope ID": in.ScopeId, "Auth Method ID": in.AuthMethodId, "Auth Method Name": in.AuthMethodName, @@ -170,7 +170,7 @@ type ScopeInfo struct { } func generateInitialScopeTableOutput(in *ScopeInfo) string { - nonAttributeMap := map[string]interface{}{ + nonAttributeMap := map[string]any{ "Scope ID": in.ScopeId, "Type": in.Type, "Name": in.Name, @@ -204,7 +204,7 @@ type HostInfo struct { } func generateInitialHostResourcesTableOutput(in *HostInfo) string { - nonAttributeMap := map[string]interface{}{ + nonAttributeMap := map[string]any{ "Host Catalog ID": in.HostCatalogId, "Host Catalog Name": in.HostCatalogName, "Host Set ID": in.HostSetId, @@ -242,7 +242,7 @@ type TargetInfo struct { } func generateInitialTargetTableOutput(in *TargetInfo) string { - nonAttributeMap := map[string]interface{}{ + nonAttributeMap := map[string]any{ "Target ID": in.TargetId, "Default Port": in.DefaultPort, "Session Max Seconds": in.SessionMaxSeconds, diff --git a/internal/cmd/commands/database/init.go b/internal/cmd/commands/database/init.go index 5c7e502542..1c83407fe1 100644 --- a/internal/cmd/commands/database/init.go +++ b/internal/cmd/commands/database/init.go @@ -297,9 +297,9 @@ func (c *InitCommand) Run(args []string) (retCode int) { c.UI.Info("Global-scope KMS keys successfully created.") } - var jsonMap map[string]interface{} + var jsonMap map[string]any if base.Format(c.UI) == "json" { - jsonMap = make(map[string]interface{}) + jsonMap = make(map[string]any) defer func() { b, err := base.JsonFormatter{}.Format(jsonMap) if err != nil { diff --git a/internal/cmd/commands/groupscmd/funcs.go b/internal/cmd/commands/groupscmd/funcs.go index 95db132e61..1149d518dd 100644 --- a/internal/cmd/commands/groupscmd/funcs.go +++ b/internal/cmd/commands/groupscmd/funcs.go @@ -206,7 +206,7 @@ func (c *Command) printListTable(items []*groups.Group) string { } func printItemTable(item *groups.Group, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if item.Id != "" { nonAttributeMap["ID"] = item.Id } @@ -228,10 +228,10 @@ func printItemTable(item *groups.Group, resp *api.Response) string { maxLength := base.MaxAttributesLength(nonAttributeMap, nil, nil) - var groupMaps []map[string]interface{} + var groupMaps []map[string]any if len(item.Members) > 0 { for _, member := range item.Members { - m := map[string]interface{}{ + m := map[string]any{ "ID": member.Id, "Scope ID": member.ScopeId, } diff --git a/internal/cmd/commands/hostcatalogscmd/funcs.go b/internal/cmd/commands/hostcatalogscmd/funcs.go index 05c8566106..b897a076cb 100644 --- a/internal/cmd/commands/hostcatalogscmd/funcs.go +++ b/internal/cmd/commands/hostcatalogscmd/funcs.go @@ -120,7 +120,7 @@ func (c *Command) printListTable(items []*hostcatalogs.HostCatalog) string { } func printItemTable(item *hostcatalogs.HostCatalog, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if item.Id != "" { nonAttributeMap["ID"] = item.Id } diff --git a/internal/cmd/commands/hostscmd/funcs.go b/internal/cmd/commands/hostscmd/funcs.go index 0f481e6cdc..d7b7c888e6 100644 --- a/internal/cmd/commands/hostscmd/funcs.go +++ b/internal/cmd/commands/hostscmd/funcs.go @@ -114,7 +114,7 @@ func (c *Command) printListTable(items []*hosts.Host) string { } func printItemTable(item *hosts.Host, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if item.Id != "" { nonAttributeMap["ID"] = item.Id } diff --git a/internal/cmd/commands/hostsetscmd/funcs.go b/internal/cmd/commands/hostsetscmd/funcs.go index 2439c96b36..b4bc1701e6 100644 --- a/internal/cmd/commands/hostsetscmd/funcs.go +++ b/internal/cmd/commands/hostsetscmd/funcs.go @@ -244,7 +244,7 @@ func (c *Command) printListTable(items []*hostsets.HostSet) string { } func printItemTable(item *hostsets.HostSet, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if item.Id != "" { nonAttributeMap["ID"] = item.Id } diff --git a/internal/cmd/commands/managedgroupscmd/funcs.go b/internal/cmd/commands/managedgroupscmd/funcs.go index 9dd0c28d6b..b79ca88755 100644 --- a/internal/cmd/commands/managedgroupscmd/funcs.go +++ b/internal/cmd/commands/managedgroupscmd/funcs.go @@ -63,7 +63,7 @@ func (c *Command) printListTable(items []*managedgroups.ManagedGroup) string { } func printItemTable(item *managedgroups.ManagedGroup, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if item.Id != "" { nonAttributeMap["ID"] = item.Id } diff --git a/internal/cmd/commands/managedgroupscmd/oidc_funcs.go b/internal/cmd/commands/managedgroupscmd/oidc_funcs.go index a9f28de535..d8e3f7bf49 100644 --- a/internal/cmd/commands/managedgroupscmd/oidc_funcs.go +++ b/internal/cmd/commands/managedgroupscmd/oidc_funcs.go @@ -88,7 +88,7 @@ func extraOidcFlagsHandlingFuncImpl(c *OidcCommand, _ *base.FlagSets, opts *[]ma c.UI.Error(fmt.Sprintf("Error when parsing filter to check validity: %v", err)) return false } - *opts = append(*opts, managedgroups.WithAttributes(map[string]interface{}{filterFlagName: c.flagFilter})) + *opts = append(*opts, managedgroups.WithAttributes(map[string]any{filterFlagName: c.flagFilter})) } return true diff --git a/internal/cmd/commands/rolescmd/funcs.go b/internal/cmd/commands/rolescmd/funcs.go index 272978bff6..1a966a091a 100644 --- a/internal/cmd/commands/rolescmd/funcs.go +++ b/internal/cmd/commands/rolescmd/funcs.go @@ -323,7 +323,7 @@ func (c *Command) printListTable(items []*roles.Role) string { } func printItemTable(item *roles.Role, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if item.Id != "" { nonAttributeMap["ID"] = item.Id } diff --git a/internal/cmd/commands/scopescmd/funcs.go b/internal/cmd/commands/scopescmd/funcs.go index c6f2e13faa..8b76acba43 100644 --- a/internal/cmd/commands/scopescmd/funcs.go +++ b/internal/cmd/commands/scopescmd/funcs.go @@ -129,7 +129,7 @@ func (c *Command) printListTable(items []*scopes.Scope) string { } func printItemTable(item *scopes.Scope, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if item.Id != "" { nonAttributeMap["ID"] = item.Id } diff --git a/internal/cmd/commands/server/worker_shutdown_reload_test.go b/internal/cmd/commands/server/worker_shutdown_reload_test.go index 7982393eba..014c6e59d5 100644 --- a/internal/cmd/commands/server/worker_shutdown_reload_test.go +++ b/internal/cmd/commands/server/worker_shutdown_reload_test.go @@ -131,7 +131,7 @@ func setAuthToken(ctx context.Context, t *testing.T, client *api.Client) { ctx, "ampw_1234567890", "login", - map[string]interface{}{ + map[string]any{ "login_name": "admin", "password": "passpass", }, diff --git a/internal/cmd/commands/sessionscmd/funcs.go b/internal/cmd/commands/sessionscmd/funcs.go index 0f112c6f7a..16fdb100f1 100644 --- a/internal/cmd/commands/sessionscmd/funcs.go +++ b/internal/cmd/commands/sessionscmd/funcs.go @@ -167,7 +167,7 @@ func (c *Command) printListTable(items []*sessions.Session) string { } func printItemTable(item *sessions.Session, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if item.Id != "" { nonAttributeMap["ID"] = item.Id } @@ -213,10 +213,10 @@ func printItemTable(item *sessions.Session, resp *api.Response) string { maxLength := base.MaxAttributesLength(nonAttributeMap, nil, nil) - var statesMaps []map[string]interface{} + var statesMaps []map[string]any if len(item.States) > 0 { for _, state := range item.States { - m := map[string]interface{}{ + m := map[string]any{ "Status": state.Status, "Start Time": state.StartTime.Local().Format(time.RFC1123), } diff --git a/internal/cmd/commands/targetscmd/funcs.go b/internal/cmd/commands/targetscmd/funcs.go index a72e17ae89..6937b3086a 100644 --- a/internal/cmd/commands/targetscmd/funcs.go +++ b/internal/cmd/commands/targetscmd/funcs.go @@ -494,7 +494,7 @@ func (c *Command) printListTable(items []*targets.Target) string { } func printItemTable(item *targets.Target, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if item.Id != "" { nonAttributeMap["ID"] = item.Id } @@ -530,10 +530,10 @@ func printItemTable(item *targets.Target, resp *api.Response) string { maxLength := base.MaxAttributesLength(nonAttributeMap, item.Attributes, keySubstMap) - var hostSourceMaps []map[string]interface{} + var hostSourceMaps []map[string]any if len(item.HostSources) > 0 { for _, set := range item.HostSources { - m := map[string]interface{}{ + m := map[string]any{ "ID": set.Id, "Host Catalog ID": set.HostCatalogId, } @@ -544,14 +544,14 @@ func printItemTable(item *targets.Target, resp *api.Response) string { } } - var credentialSourceMaps map[credential.Purpose][]map[string]interface{} + var credentialSourceMaps map[credential.Purpose][]map[string]any if len(item.BrokeredCredentialSources) > 0 { if credentialSourceMaps == nil { - credentialSourceMaps = make(map[credential.Purpose][]map[string]interface{}) + credentialSourceMaps = make(map[credential.Purpose][]map[string]any) } - var brokeredCredentialSourceMaps []map[string]interface{} + var brokeredCredentialSourceMaps []map[string]any for _, source := range item.BrokeredCredentialSources { - m := map[string]interface{}{ + m := map[string]any{ "ID": source.Id, "Credential Store ID": source.CredentialStoreId, } @@ -564,11 +564,11 @@ func printItemTable(item *targets.Target, resp *api.Response) string { } if len(item.InjectedApplicationCredentialSources) > 0 { if credentialSourceMaps == nil { - credentialSourceMaps = make(map[credential.Purpose][]map[string]interface{}) + credentialSourceMaps = make(map[credential.Purpose][]map[string]any) } - var injectedApplicationCredentialSourceMaps []map[string]interface{} + var injectedApplicationCredentialSourceMaps []map[string]any for _, source := range item.InjectedApplicationCredentialSources { - m := map[string]interface{}{ + m := map[string]any{ "ID": source.Id, "Credential Store ID": source.CredentialStoreId, } @@ -656,7 +656,7 @@ func printCustomActionOutputImpl(c *Command) (bool, error) { case "table": var ret []string - nonAttributeMap := map[string]interface{}{ + nonAttributeMap := map[string]any{ "Session ID": item.SessionId, "Target ID": item.TargetId, "Scope ID": item.Scope.Id, @@ -810,7 +810,7 @@ func exampleOutput() string { CredentialStoreId: "clvlt_0987654321", }, }, - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "default_port": 22, }, } diff --git a/internal/cmd/commands/userscmd/funcs.go b/internal/cmd/commands/userscmd/funcs.go index 86111fdd10..62482fce63 100644 --- a/internal/cmd/commands/userscmd/funcs.go +++ b/internal/cmd/commands/userscmd/funcs.go @@ -228,7 +228,7 @@ func (c *Command) printListTable(items []*users.User) string { } func printItemTable(item *users.User, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if item.Id != "" { nonAttributeMap["ID"] = item.Id } @@ -262,10 +262,10 @@ func printItemTable(item *users.User, resp *api.Response) string { maxLength := base.MaxAttributesLength(nonAttributeMap, nil, nil) - var userMaps []map[string]interface{} + var userMaps []map[string]any if len(item.Accounts) > 0 { for _, account := range item.Accounts { - a := map[string]interface{}{ + a := map[string]any{ "ID": account.Id, "Scope ID": account.ScopeId, } diff --git a/internal/cmd/commands/version/version.go b/internal/cmd/commands/version/version.go index a615e97687..effa85f95a 100644 --- a/internal/cmd/commands/version/version.go +++ b/internal/cmd/commands/version/version.go @@ -57,7 +57,7 @@ func (c *Command) Run(args []string) int { return base.CommandSuccess } - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if verInfo.CgoEnabled { nonAttributeMap["Cgo Enabled"] = verInfo.CgoEnabled } diff --git a/internal/cmd/commands/workerscmd/funcs.go b/internal/cmd/commands/workerscmd/funcs.go index b803f131b6..dbcd79f917 100644 --- a/internal/cmd/commands/workerscmd/funcs.go +++ b/internal/cmd/commands/workerscmd/funcs.go @@ -238,7 +238,7 @@ func (c *Command) printListTable(items []*workers.Worker) string { } func printItemTable(item *workers.Worker, resp *api.Response) string { - nonAttributeMap := map[string]interface{}{} + nonAttributeMap := map[string]any{} if item.Id != "" { nonAttributeMap["ID"] = item.Id } diff --git a/internal/cmd/common/flags.go b/internal/cmd/common/flags.go index 2f0420e1a1..eaa592594f 100644 --- a/internal/cmd/common/flags.go +++ b/internal/cmd/common/flags.go @@ -272,7 +272,7 @@ var jsonNumberRegex = regexp.MustCompile(`^-?(?:0|[1-9]\d*)(?:\.\d+)?$`) // HandleAttributeFlags takes in a command and a func to call for default (that // is, set to nil) and non-default values. Suffix can be used to allow this // logic to be used for various needs, e.g. -attr vs -secret. -func HandleAttributeFlags(c *base.Command, suffix, fullField string, sepFields []base.CombinedSliceFlagValue, defaultFunc func(), setFunc func(map[string]interface{})) error { +func HandleAttributeFlags(c *base.Command, suffix, fullField string, sepFields []base.CombinedSliceFlagValue, defaultFunc func(), setFunc func(map[string]any)) error { // If we were given a fullly defined field, use that as-is switch fullField { case "": @@ -286,7 +286,7 @@ func HandleAttributeFlags(c *base.Command, suffix, fullField string, sepFields [ return fmt.Errorf("error parsing %s flag as a URL: %w", suffix, err) } // We should be able to parse the string as a JSON object - var setMap map[string]interface{} + var setMap map[string]any if err := json.Unmarshal([]byte(parsedString), &setMap); err != nil { return fmt.Errorf("error parsing %s flag as JSON: %w", suffix, err) } @@ -294,7 +294,7 @@ func HandleAttributeFlags(c *base.Command, suffix, fullField string, sepFields [ return nil } - setMap := map[string]interface{}{} + setMap := map[string]any{} for _, field := range sepFields { if len(field.Keys) == 0 { @@ -302,7 +302,7 @@ func HandleAttributeFlags(c *base.Command, suffix, fullField string, sepFields [ continue } - var val interface{} + var val any var err error // First, perform any needed parsing if we are given the type @@ -367,7 +367,7 @@ func HandleAttributeFlags(c *base.Command, suffix, fullField string, sepFields [ } case strings.HasPrefix(field.Value, "["): // serialized JSON array - var s []interface{} + var s []any u := json.NewDecoder(bytes.NewBufferString(field.Value)) u.UseNumber() if err := u.Decode(&s); err != nil { @@ -376,7 +376,7 @@ func HandleAttributeFlags(c *base.Command, suffix, fullField string, sepFields [ val = s case strings.HasPrefix(field.Value, "{"): // serialized JSON map - var m map[string]interface{} + var m map[string]any u := json.NewDecoder(bytes.NewBufferString(field.Value)) u.UseNumber() if err := u.Decode(&m); err != nil { @@ -413,14 +413,14 @@ func HandleAttributeFlags(c *base.Command, suffix, fullField string, sepFields [ // Nothing currently exists currMap[segment] = val - case []interface{}: + case []any: // It's already a slice, so just append currMap[segment] = append(t, val) default: // It's not a slice, so create a new slice with the // exisitng and new values - currMap[segment] = []interface{}{t, val} + currMap[segment] = []any{t, val} } default: @@ -429,11 +429,11 @@ func HandleAttributeFlags(c *base.Command, suffix, fullField string, sepFields [ case nil: // We haven't hit this segment before, so create a new // object leading off of it and set it to current - newMap := map[string]interface{}{} + newMap := map[string]any{} currMap[segment] = newMap currMap = newMap - case map[string]interface{}: + case map[string]any: // We've seen this before and already have a map so just set // that as our new location currMap = t diff --git a/internal/cmd/common/flags_test.go b/internal/cmd/common/flags_test.go index 80d2dc91b8..7108eb5d04 100644 --- a/internal/cmd/common/flags_test.go +++ b/internal/cmd/common/flags_test.go @@ -176,7 +176,7 @@ func TestHandleAttributeFlags(t *testing.T) { tests := []struct { name string args []base.CombinedSliceFlagValue - expectedMap map[string]interface{} + expectedMap map[string]any expectedErr string }{ { @@ -193,7 +193,7 @@ func TestHandleAttributeFlags(t *testing.T) { Value: `"baz"`, }, }, - expectedMap: map[string]interface{}{ + expectedMap: map[string]any{ "foo": "bar", "bar": "baz", }, @@ -212,7 +212,7 @@ func TestHandleAttributeFlags(t *testing.T) { Value: "5", }, }, - expectedMap: map[string]interface{}{ + expectedMap: map[string]any{ "foo": float64(-1.2), "bar": int64(5), }, @@ -253,7 +253,7 @@ func TestHandleAttributeFlags(t *testing.T) { Value: "false", }, }, - expectedMap: map[string]interface{}{ + expectedMap: map[string]any{ "foo": true, "bar": false, }, @@ -318,26 +318,26 @@ func TestHandleAttributeFlags(t *testing.T) { Value: `{"b": true, "n": 6, "s": "scoopde", "a": ["bar"], "m": {"hip": "hop"}}`, }, }, - expectedMap: map[string]interface{}{ + expectedMap: map[string]any{ "b1": true, "b2": false, "s1": "scoopde", "s2": "woop", "n1": float64(-1.2), "n2": int64(5), - "a": []interface{}{ + "a": []any{ "foo", json.Number("1.5"), true, - []interface{}{"bar"}, - map[string]interface{}{"hip": "hop"}, + []any{"bar"}, + map[string]any{"hip": "hop"}, }, - "m": map[string]interface{}{ + "m": map[string]any{ "b": true, "n": json.Number("6"), "s": "scoopde", - "a": []interface{}{"bar"}, - "m": map[string]interface{}{"hip": "hop"}, + "a": []any{"bar"}, + "m": map[string]any{"hip": "hop"}, }, "nil": nil, }, @@ -381,14 +381,14 @@ func TestHandleAttributeFlags(t *testing.T) { Value: "null", }, }, - expectedMap: map[string]interface{}{ - "bools": []interface{}{true, false}, - "strings": map[string]interface{}{ + expectedMap: map[string]any{ + "bools": []any{true, false}, + "strings": map[string]any{ "s1": "scoopde", "s2": nil, }, - "numbers": map[string]interface{}{ - "reps": []interface{}{float64(-1.2), int64(5)}, + "numbers": map[string]any{ + "reps": []any{float64(-1.2), int64(5)}, }, }, }, @@ -402,7 +402,7 @@ func TestHandleAttributeFlags(t *testing.T) { // state over; just like in the real CLI where each run would have // pristine state. c := new(base.Command) - var outMap map[string]interface{} + var outMap map[string]any args := make([]base.CombinedSliceFlagValue, 0, len(tt.args)) for _, arg := range tt.args { @@ -410,7 +410,7 @@ func TestHandleAttributeFlags(t *testing.T) { args = append(args, arg) } - err := HandleAttributeFlags(c, typ, "", args, func() {}, func(in map[string]interface{}) { outMap = in }) + err := HandleAttributeFlags(c, typ, "", args, func() {}, func(in map[string]any) { outMap = in }) if tt.expectedErr != "" { require.Error(err) assert.Contains(err.Error(), tt.expectedErr) diff --git a/internal/cmd/config/config.go b/internal/cmd/config/config.go index f5e503b24d..1e1eff9b6c 100644 --- a/internal/cmd/config/config.go +++ b/internal/cmd/config/config.go @@ -145,18 +145,18 @@ type Controller struct { Scheduler *Scheduler `hcl:"scheduler"` // AuthTokenTimeToLive is the total valid lifetime of a token denoted by time.Duration - AuthTokenTimeToLive interface{} `hcl:"auth_token_time_to_live"` + AuthTokenTimeToLive any `hcl:"auth_token_time_to_live"` AuthTokenTimeToLiveDuration time.Duration // AuthTokenTimeToStale is the total time a token can go unused before becoming invalid // denoted by time.Duration - AuthTokenTimeToStale interface{} `hcl:"auth_token_time_to_stale"` + AuthTokenTimeToStale any `hcl:"auth_token_time_to_stale"` AuthTokenTimeToStaleDuration time.Duration // GracefulShutdownWait is the amount of time that we'll wait before actually // starting the Controller shutdown. This allows the health endpoint to // return a status code to indicate that the instance is shutting down. - GracefulShutdownWait interface{} `hcl:"graceful_shutdown_wait_duration"` + GracefulShutdownWait any `hcl:"graceful_shutdown_wait_duration"` GracefulShutdownWaitDuration time.Duration // StatusGracePeriod represents the period of time (as a duration) that the @@ -197,14 +197,14 @@ type Worker struct { // The ControllersRaw field is deprecated and users should use InitialUpstreamsRaw instead. // TODO: remove this field when support is discontinued. - ControllersRaw interface{} `hcl:"controllers"` + ControllersRaw any `hcl:"controllers"` // We use a raw interface for parsing so that people can use JSON-like // syntax that maps directly to the filter input or possibly more familiar // key=value syntax, as well as accepting a string denoting an env or file // pointer. This is trued up in the Parse function below. Tags map[string][]string `hcl:"-"` - TagsRaw interface{} `hcl:"tags"` + TagsRaw any `hcl:"tags"` // StatusGracePeriod represents the period of time (as a duration) that the // worker will wait before disconnecting connections if it cannot make a @@ -226,10 +226,10 @@ type Database struct { Url string `hcl:"url"` MigrationUrl string `hcl:"migration_url"` MaxOpenConnections int `hcl:"-"` - MaxOpenConnectionsRaw interface{} `hcl:"max_open_connections"` + MaxOpenConnectionsRaw any `hcl:"max_open_connections"` MaxIdleConnections *int `hcl:"-"` - MaxIdleConnectionsRaw interface{} `hcl:"max_idle_connections"` - ConnMaxIdleTime interface{} `hcl:"max_idle_time"` + MaxIdleConnectionsRaw any `hcl:"max_idle_connections"` + ConnMaxIdleTime any `hcl:"max_idle_time"` ConnMaxIdleTimeDuration *time.Duration `hcl:"-"` // SkipSharedLockAcquisition allows skipping grabbing the database shared @@ -244,13 +244,13 @@ type Scheduler struct { // JobRunInterval is the time interval between waking up the // scheduler to run pending jobs. // - JobRunInterval interface{} `hcl:"job_run_interval"` + JobRunInterval any `hcl:"job_run_interval"` JobRunIntervalDuration time.Duration // MonitorInterval is the time interval between waking up the // scheduler to monitor for jobs that are defunct. // - MonitorInterval interface{} `hcl:"monitor_interval"` + MonitorInterval any `hcl:"monitor_interval"` MonitorIntervalDuration time.Duration } @@ -593,7 +593,7 @@ func Parse(d string) (*Config, error) { return nil, fmt.Errorf("Error parsing worker tags: %w", err) } - var temp []map[string]interface{} + var temp []map[string]any err = hcl.Decode(&temp, rawTags) if err != nil { return nil, fmt.Errorf("Error decoding raw worker tags: %w", err) @@ -606,7 +606,7 @@ func Parse(d string) (*Config, error) { // HCL allows multiple labeled blocks with the same name, turning it // into a slice of maps, hence the slice here. This format is the // one that ends up matching the JSON that we use in the expression. - case []map[string]interface{}: + case []map[string]any: for _, m := range t { for k, v := range m { // We allow the user to pass in only the keys in HCL, and @@ -642,7 +642,7 @@ func Parse(d string) (*Config, error) { // However for those that are used to other systems, we also accept // key=value pairs - case []interface{}: + case []any: var strs []string if err := mapstructure.WeakDecode(t, &strs); err != nil { return nil, fmt.Errorf("Error decoding the worker's %q section: %w", "tags", err) @@ -778,7 +778,7 @@ func parseWorkerUpstreams(c *Config) ([]string, error) { } switch t := rawUpstreams.(type) { - case []interface{}: // An array was configured directly in Boundary's HCL Config file. + case []any: var upstreams []string err := mapstructure.WeakDecode(rawUpstreams, &upstreams) if err != nil { @@ -887,14 +887,14 @@ func parseEventing(eventObj *ast.ObjectItem) (*event.EventerConfig, error) { // Specifically, the fields that this method strips are: // - KMS.Config // - Telemetry.CirconusAPIToken -func (c *Config) Sanitized() map[string]interface{} { +func (c *Config) Sanitized() map[string]any { // Create shared config if it doesn't exist (e.g. in tests) so that map // keys are actually populated if c.SharedConfig == nil { c.SharedConfig = new(configutil.SharedConfig) } sharedResult := c.SharedConfig.Sanitized() - result := map[string]interface{}{} + result := map[string]any{} for k, v := range sharedResult { result[k] = v } diff --git a/internal/cmd/config/config_load_test.go b/internal/cmd/config/config_load_test.go index a5d7b9914a..9546db6a64 100644 --- a/internal/cmd/config/config_load_test.go +++ b/internal/cmd/config/config_load_test.go @@ -26,7 +26,7 @@ func TestLoad(t *testing.T) { EntSharedConfig: configutil.EntSharedConfig{}, Listeners: []*listenerutil.ListenerConfig{ { - RawConfig: map[string]interface{}{ + RawConfig: map[string]any{ "address": "boundary", "purpose": "api", "tls_disable": true, @@ -93,7 +93,7 @@ func TestLoad(t *testing.T) { CorsAllowedHeadersRaw: nil, }, { - RawConfig: map[string]interface{}{ + RawConfig: map[string]any{ "address": "boundary", "purpose": "cluster", "tls_disable": true, @@ -160,7 +160,7 @@ func TestLoad(t *testing.T) { CorsAllowedHeadersRaw: nil, }, { - RawConfig: map[string]interface{}{ + RawConfig: map[string]any{ "address": "boundary", "purpose": "proxy", "tls_disable": true, @@ -227,7 +227,7 @@ func TestLoad(t *testing.T) { CorsAllowedHeadersRaw: nil, }, { - RawConfig: map[string]interface{}{ + RawConfig: map[string]any{ "address": "boundary", "purpose": "ops", "tls_disable": true, @@ -351,7 +351,7 @@ func TestLoad(t *testing.T) { Description: "A worker", PublicAddr: "", InitialUpstreams: []string{"boundary:9201"}, - InitialUpstreamsRaw: []interface{}{"boundary:9201"}, + InitialUpstreamsRaw: []any{"boundary:9201"}, ControllersRaw: nil, Tags: nil, TagsRaw: nil, @@ -430,7 +430,7 @@ func TestLoad(t *testing.T) { EntSharedConfig: configutil.EntSharedConfig{}, Listeners: []*listenerutil.ListenerConfig{ { - RawConfig: map[string]interface{}{ + RawConfig: map[string]any{ "address": "boundary", "purpose": "api", "tls_disable": true, @@ -497,7 +497,7 @@ func TestLoad(t *testing.T) { CorsAllowedHeadersRaw: nil, }, { - RawConfig: map[string]interface{}{ + RawConfig: map[string]any{ "address": "boundary", "purpose": "cluster", "tls_disable": true, @@ -564,7 +564,7 @@ func TestLoad(t *testing.T) { CorsAllowedHeadersRaw: nil, }, { - RawConfig: map[string]interface{}{ + RawConfig: map[string]any{ "address": "boundary", "purpose": "ops", "tls_disable": true, @@ -631,7 +631,7 @@ func TestLoad(t *testing.T) { CorsAllowedHeadersRaw: nil, }, { - RawConfig: map[string]interface{}{ + RawConfig: map[string]any{ "address": "boundary", "purpose": "proxy", "tls_disable": true, @@ -755,7 +755,7 @@ func TestLoad(t *testing.T) { Description: "A worker", PublicAddr: "", InitialUpstreams: []string{"boundary:9201"}, - InitialUpstreamsRaw: []interface{}{"boundary:9201"}, + InitialUpstreamsRaw: []any{"boundary:9201"}, ControllersRaw: nil, Tags: nil, TagsRaw: nil, @@ -834,7 +834,7 @@ func TestLoad(t *testing.T) { EntSharedConfig: configutil.EntSharedConfig{}, Listeners: []*listenerutil.ListenerConfig{ { - RawConfig: map[string]interface{}{ + RawConfig: map[string]any{ "address": "boundary", "purpose": "api", "tls_disable": true, @@ -901,7 +901,7 @@ func TestLoad(t *testing.T) { CorsAllowedHeadersRaw: nil, }, { - RawConfig: map[string]interface{}{ + RawConfig: map[string]any{ "address": "boundary", "purpose": "cluster", "tls_disable": true, @@ -968,7 +968,7 @@ func TestLoad(t *testing.T) { CorsAllowedHeadersRaw: nil, }, { - RawConfig: map[string]interface{}{ + RawConfig: map[string]any{ "address": "boundary", "purpose": "ops", "tls_disable": true, @@ -1035,7 +1035,7 @@ func TestLoad(t *testing.T) { CorsAllowedHeadersRaw: nil, }, { - RawConfig: map[string]interface{}{ + RawConfig: map[string]any{ "address": "boundary", "purpose": "proxy", "tls_disable": true, @@ -1159,7 +1159,7 @@ func TestLoad(t *testing.T) { Description: "A worker", PublicAddr: "", InitialUpstreams: []string{"boundary:9201"}, - InitialUpstreamsRaw: []interface{}{"boundary:9201"}, + InitialUpstreamsRaw: []any{"boundary:9201"}, ControllersRaw: nil, Tags: nil, TagsRaw: nil, @@ -1238,7 +1238,7 @@ func TestLoad(t *testing.T) { EntSharedConfig: configutil.EntSharedConfig{}, Listeners: []*listenerutil.ListenerConfig{ { - RawConfig: map[string]interface{}{ + RawConfig: map[string]any{ "address": "boundary", "purpose": "api", "tls_disable": true, @@ -1305,7 +1305,7 @@ func TestLoad(t *testing.T) { CorsAllowedHeadersRaw: nil, }, { - RawConfig: map[string]interface{}{ + RawConfig: map[string]any{ "address": "boundary", "purpose": "cluster", "tls_disable": true, @@ -1372,7 +1372,7 @@ func TestLoad(t *testing.T) { CorsAllowedHeadersRaw: nil, }, { - RawConfig: map[string]interface{}{ + RawConfig: map[string]any{ "address": "boundary", "purpose": "proxy", "tls_disable": true, @@ -1439,7 +1439,7 @@ func TestLoad(t *testing.T) { CorsAllowedHeadersRaw: nil, }, { - RawConfig: map[string]interface{}{ + RawConfig: map[string]any{ "address": "boundary", "purpose": "ops", "tls_disable": true, @@ -1563,7 +1563,7 @@ func TestLoad(t *testing.T) { Description: "A worker", PublicAddr: "", InitialUpstreams: []string{"boundary:9201"}, - InitialUpstreamsRaw: []interface{}{"boundary:9201"}, + InitialUpstreamsRaw: []any{"boundary:9201"}, ControllersRaw: nil, Tags: nil, TagsRaw: nil, diff --git a/internal/cmd/config/config_test.go b/internal/cmd/config/config_test.go index 48858384f5..115e70b06b 100644 --- a/internal/cmd/config/config_test.go +++ b/internal/cmd/config/config_test.go @@ -193,7 +193,7 @@ func TestDevWorker(t *testing.T) { Name: "w_1234567890", Description: "A default worker created in dev mode", InitialUpstreams: []string{"127.0.0.1"}, - InitialUpstreamsRaw: []interface{}{"127.0.0.1"}, + InitialUpstreamsRaw: []any{"127.0.0.1"}, Tags: map[string][]string{ "type": {"dev", "local"}, }, @@ -399,7 +399,7 @@ func TestDevCombined(t *testing.T) { Name: "w_1234567890", Description: "A default worker created in dev mode", InitialUpstreams: []string{"127.0.0.1"}, - InitialUpstreamsRaw: []interface{}{"127.0.0.1"}, + InitialUpstreamsRaw: []any{"127.0.0.1"}, Tags: map[string][]string{ "type": {"dev", "local"}, }, diff --git a/internal/credential/credential.go b/internal/credential/credential.go index c29710b629..09218994da 100644 --- a/internal/credential/credential.go +++ b/internal/credential/credential.go @@ -67,7 +67,7 @@ var ValidPurposes = []Purpose{ } // SecretData represents secret data. -type SecretData interface{} +type SecretData any // Credential is an entity containing secret data. type Credential interface { diff --git a/internal/credential/static/repository_credential.go b/internal/credential/static/repository_credential.go index 2c423e5b82..b1d90f14a2 100644 --- a/internal/credential/static/repository_credential.go +++ b/internal/credential/static/repository_credential.go @@ -385,7 +385,7 @@ func (r *Repository) UpdateUsernamePasswordCredential(ctx context.Context, } } dbMask, nullFields := dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ nameField: c.Name, descriptionField: c.Description, usernameField: c.Username, @@ -501,7 +501,7 @@ func (r *Repository) UpdateSshPrivateKeyCredential(ctx context.Context, } } dbMask, nullFields := dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ nameField: c.Name, descriptionField: c.Description, usernameField: c.Username, @@ -649,7 +649,7 @@ func (r *Repository) UpdateJsonCredential(ctx context.Context, } } dbMask, nullFields := dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ nameField: c.Name, descriptionField: c.Description, objectField: c.Object, @@ -727,19 +727,19 @@ func (r *Repository) ListCredentials(ctx context.Context, storeId string, opt .. } var upCreds []*UsernamePasswordCredential - err := r.reader.SearchWhere(ctx, &upCreds, "store_id = ?", []interface{}{storeId}, db.WithLimit(limit)) + err := r.reader.SearchWhere(ctx, &upCreds, "store_id = ?", []any{storeId}, db.WithLimit(limit)) if err != nil { return nil, errors.Wrap(ctx, err, op) } var spkCreds []*SshPrivateKeyCredential - err = r.reader.SearchWhere(ctx, &spkCreds, "store_id = ?", []interface{}{storeId}, db.WithLimit(limit)) + err = r.reader.SearchWhere(ctx, &spkCreds, "store_id = ?", []any{storeId}, db.WithLimit(limit)) if err != nil { return nil, errors.Wrap(ctx, err, op) } var jsonCreds []*JsonCredential - err = r.reader.SearchWhere(ctx, &jsonCreds, "store_id = ?", []interface{}{storeId}, db.WithLimit(limit)) + err = r.reader.SearchWhere(ctx, &jsonCreds, "store_id = ?", []any{storeId}, db.WithLimit(limit)) if err != nil { return nil, errors.Wrap(ctx, err, op) } @@ -786,7 +786,7 @@ func (r *Repository) DeleteCredential(ctx context.Context, projectId, id string, return db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "no project id") } - var input interface{} + var input any var md oplog.Metadata switch subtypes.SubtypeFromId(credential.Domain, id) { case credential.UsernamePasswordSubtype: diff --git a/internal/credential/static/repository_credential_store.go b/internal/credential/static/repository_credential_store.go index 11e0ca9c5b..9bc2491486 100644 --- a/internal/credential/static/repository_credential_store.go +++ b/internal/credential/static/repository_credential_store.go @@ -125,7 +125,7 @@ func (r *Repository) UpdateCredentialStore(ctx context.Context, cs *CredentialSt } } dbMask, nullFields := dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ nameField: cs.Name, descriptionField: cs.Description, }, @@ -182,7 +182,7 @@ func (r *Repository) ListCredentialStores(ctx context.Context, projectIds []stri limit = opts.withLimit } var credentialStores []*CredentialStore - err := r.reader.SearchWhere(ctx, &credentialStores, "project_id in (?)", []interface{}{projectIds}, db.WithLimit(limit)) + err := r.reader.SearchWhere(ctx, &credentialStores, "project_id in (?)", []any{projectIds}, db.WithLimit(limit)) if err != nil { return nil, errors.Wrap(ctx, err, op) } diff --git a/internal/credential/static/repository_credentials.go b/internal/credential/static/repository_credentials.go index 5a9746aee1..97ec1b4d07 100644 --- a/internal/credential/static/repository_credentials.go +++ b/internal/credential/static/repository_credentials.go @@ -18,17 +18,17 @@ func (r *Repository) Retrieve(ctx context.Context, projectId string, ids []strin } var upCreds []*UsernamePasswordCredential - err := r.reader.SearchWhere(ctx, &upCreds, "public_id in (?)", []interface{}{ids}) + err := r.reader.SearchWhere(ctx, &upCreds, "public_id in (?)", []any{ids}) if err != nil { return nil, errors.Wrap(ctx, err, op) } var spkCreds []*SshPrivateKeyCredential - err = r.reader.SearchWhere(ctx, &spkCreds, "public_id in (?)", []interface{}{ids}) + err = r.reader.SearchWhere(ctx, &spkCreds, "public_id in (?)", []any{ids}) if err != nil { return nil, errors.Wrap(ctx, err, op) } var jsonCreds []*JsonCredential - err = r.reader.SearchWhere(ctx, &jsonCreds, "public_id in (?)", []interface{}{ids}) + err = r.reader.SearchWhere(ctx, &jsonCreds, "public_id in (?)", []any{ids}) if err != nil { return nil, errors.Wrap(ctx, err, op) } diff --git a/internal/credential/vault/client_certificate.go b/internal/credential/vault/client_certificate.go index 0813f6813a..d7c1aed49e 100644 --- a/internal/credential/vault/client_certificate.go +++ b/internal/credential/vault/client_certificate.go @@ -115,9 +115,9 @@ func (c *ClientCertificate) hmacCertificateKey(ctx context.Context, cipher wrapp return nil } -func (c *ClientCertificate) insertQuery() (query string, queryValues []interface{}) { +func (c *ClientCertificate) insertQuery() (query string, queryValues []any) { query = upsertClientCertQuery - queryValues = []interface{}{ + queryValues = []any{ sql.Named("store_id", c.StoreId), sql.Named("certificate", c.Certificate), sql.Named("certificate_key", c.CtCertificateKey), @@ -127,9 +127,9 @@ func (c *ClientCertificate) insertQuery() (query string, queryValues []interface return } -func (c *ClientCertificate) deleteQuery() (query string, queryValues []interface{}) { +func (c *ClientCertificate) deleteQuery() (query string, queryValues []any) { query = deleteClientCertQuery - queryValues = []interface{}{ + queryValues = []any{ c.StoreId, } return diff --git a/internal/credential/vault/credential.go b/internal/credential/vault/credential.go index a3e9178f77..10f390f8e0 100644 --- a/internal/credential/vault/credential.go +++ b/internal/credential/vault/credential.go @@ -117,8 +117,8 @@ func (c *Credential) oplog(op oplog.OpType) oplog.Metadata { return metadata } -func (c *Credential) insertQuery() (query string, queryValues []interface{}) { - queryValues = []interface{}{ +func (c *Credential) insertQuery() (query string, queryValues []any) { + queryValues = []any{ sql.Named("public_id", c.PublicId), sql.Named("library_id", c.LibraryId), sql.Named("session_id", c.SessionId), @@ -138,8 +138,8 @@ func (c *Credential) insertQuery() (query string, queryValues []interface{}) { return } -func (c *Credential) updateSessionQuery(purpose credential.Purpose) (query string, queryValues []interface{}) { - queryValues = []interface{}{ +func (c *Credential) updateSessionQuery(purpose credential.Purpose) (query string, queryValues []any) { + queryValues = []any{ sql.Named("public_id", c.PublicId), sql.Named("library_id", c.LibraryId), sql.Named("session_id", c.SessionId), @@ -149,8 +149,8 @@ func (c *Credential) updateSessionQuery(purpose credential.Purpose) (query strin return } -func (c *Credential) updateExpirationQuery() (query string, queryValues []interface{}) { - queryValues = []interface{}{ +func (c *Credential) updateExpirationQuery() (query string, queryValues []any) { + queryValues = []any{ int(c.expiration.Round(time.Second).Seconds()), c.PublicId, } @@ -158,8 +158,8 @@ func (c *Credential) updateExpirationQuery() (query string, queryValues []interf return } -func (c *Credential) updateStatusQuery(status CredentialStatus) (query string, queryValues []interface{}) { - queryValues = []interface{}{ +func (c *Credential) updateStatusQuery(status CredentialStatus) (query string, queryValues []any) { + queryValues = []any{ status, c.PublicId, } diff --git a/internal/credential/vault/credential_store.go b/internal/credential/vault/credential_store.go index ac549cbc21..9c2102af22 100644 --- a/internal/credential/vault/credential_store.go +++ b/internal/credential/vault/credential_store.go @@ -191,9 +191,9 @@ func (cs *CredentialStore) client(ctx context.Context) (vaultClient, error) { return c, nil } -func (cs *CredentialStore) softDeleteQuery() (query string, queryValues []interface{}) { +func (cs *CredentialStore) softDeleteQuery() (query string, queryValues []any) { query = softDeleteStoreQuery - queryValues = []interface{}{ + queryValues = []any{ cs.PublicId, } return diff --git a/internal/credential/vault/internal/sshprivatekey/sshprivatekey_test.go b/internal/credential/vault/internal/sshprivatekey/sshprivatekey_test.go index 07c81cea85..d8deac3cef 100644 --- a/internal/credential/vault/internal/sshprivatekey/sshprivatekey_test.go +++ b/internal/credential/vault/internal/sshprivatekey/sshprivatekey_test.go @@ -101,8 +101,8 @@ func TestExtract(t *testing.T) { name: "no-match-username-secret-kv2", given: args{ s: data{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + "metadata": map[string]any{}, + "data": map[string]any{ "username-wrong": "user", "private_key": string(edKey), }, @@ -116,8 +116,8 @@ func TestExtract(t *testing.T) { name: "no-match-private-key-secret-kv2", given: args{ s: data{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "user", "private_key-wrong": string(edKey), }, @@ -131,8 +131,8 @@ func TestExtract(t *testing.T) { name: "valid-kv2", given: args{ s: data{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "user", "private_key": string(edKey), }, @@ -146,8 +146,8 @@ func TestExtract(t *testing.T) { name: "valid-kv2-with-passphrase", given: args{ s: data{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "user", "private_key": string(edKey), "passphrase": "my-pass", @@ -163,7 +163,7 @@ func TestExtract(t *testing.T) { name: "no-metadata-kv2", given: args{ s: data{ - "data": map[string]interface{}{ + "data": map[string]any{ "username": "user", "private_key": string(edKey), }, @@ -178,7 +178,7 @@ func TestExtract(t *testing.T) { given: args{ s: data{ "metadata": "string", - "data": map[string]interface{}{ + "data": map[string]any{ "username": "user", "private_key": string(edKey), }, @@ -192,9 +192,9 @@ func TestExtract(t *testing.T) { name: "invalid-field-kv2", given: args{ s: data{ - "invalid": map[string]interface{}{}, - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + "invalid": map[string]any{}, + "metadata": map[string]any{}, + "data": map[string]any{ "username": "user", "private_key": string(edKey), }, @@ -210,8 +210,8 @@ func TestExtract(t *testing.T) { s: data{ "username": "default-user", "private_key": string(rsaKey), - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "kv2-user", "private_key": string(edKey), }, @@ -226,7 +226,7 @@ func TestExtract(t *testing.T) { given: args{ s: data{ "username": "default-user", - "testing": map[string]interface{}{ + "testing": map[string]any{ "private_key": string(edKey), }, }, @@ -240,7 +240,7 @@ func TestExtract(t *testing.T) { given: args{ s: data{ "private_key": string(edKey), - "testing": map[string]interface{}{ + "testing": map[string]any{ "special": "not-so-special", }, }, @@ -253,15 +253,15 @@ func TestExtract(t *testing.T) { name: "all-json-pointer", given: args{ s: data{ - "first-path": map[string]interface{}{ - "deeper-path": map[string]interface{}{ + "first-path": map[string]any{ + "deeper-path": map[string]any{ "my-special-user": "you-found-me", }, }, - "testing": map[string]interface{}{ + "testing": map[string]any{ "private_key": string(edKey), }, - "hidden": map[string]interface{}{ + "hidden": map[string]any{ "pass": "my-pass", }, }, diff --git a/internal/credential/vault/internal/usernamepassword/usernamepassword.go b/internal/credential/vault/internal/usernamepassword/usernamepassword.go index 7aa1ae3c64..7e42bfcd1b 100644 --- a/internal/credential/vault/internal/usernamepassword/usernamepassword.go +++ b/internal/credential/vault/internal/usernamepassword/usernamepassword.go @@ -7,7 +7,7 @@ import ( ) type ( - data map[string]interface{} + data map[string]any // extractFunc attempts to extract the username and password // from sd using the provided attribute names, using a known @@ -96,18 +96,18 @@ func kv2Extract(sd data, usernameAttr, passwordAttr string) (username string, pa return "", "" } - var data, metadata map[string]interface{} + var data, metadata map[string]any for k, v := range sd { switch k { case "data": var ok bool - if data, ok = v.(map[string]interface{}); !ok { + if data, ok = v.(map[string]any); !ok { // data field should be of type map[string]interface{} in KV-v2 return "", "" } case "metadata": var ok bool - if metadata, ok = v.(map[string]interface{}); !ok { + if metadata, ok = v.(map[string]any); !ok { // metadata field should be of type map[string]interface{} in KV-v2 return "", "" } diff --git a/internal/credential/vault/internal/usernamepassword/usernamepassword_test.go b/internal/credential/vault/internal/usernamepassword/usernamepassword_test.go index 582308c3f5..bcbc444705 100644 --- a/internal/credential/vault/internal/usernamepassword/usernamepassword_test.go +++ b/internal/credential/vault/internal/usernamepassword/usernamepassword_test.go @@ -80,8 +80,8 @@ func TestBaseToUsrPass(t *testing.T) { name: "no-match-username-secret-kv2", given: args{ s: data{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + "metadata": map[string]any{}, + "data": map[string]any{ "username-wrong": "user", "password": "pass", }, @@ -95,8 +95,8 @@ func TestBaseToUsrPass(t *testing.T) { name: "no-match-password-secret-kv2", given: args{ s: data{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "user", "password-wrong": "pass", }, @@ -110,8 +110,8 @@ func TestBaseToUsrPass(t *testing.T) { name: "valid-kv2", given: args{ s: data{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "user", "password": "pass", }, @@ -125,7 +125,7 @@ func TestBaseToUsrPass(t *testing.T) { name: "no-metadata-kv2", given: args{ s: data{ - "data": map[string]interface{}{ + "data": map[string]any{ "username": "user", "password": "pass", }, @@ -140,7 +140,7 @@ func TestBaseToUsrPass(t *testing.T) { given: args{ s: data{ "metadata": "string", - "data": map[string]interface{}{ + "data": map[string]any{ "username": "user", "password": "pass", }, @@ -154,9 +154,9 @@ func TestBaseToUsrPass(t *testing.T) { name: "invalid-field-kv2", given: args{ s: data{ - "invalid": map[string]interface{}{}, - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + "invalid": map[string]any{}, + "metadata": map[string]any{}, + "data": map[string]any{ "username": "user", "password": "pass", }, @@ -172,8 +172,8 @@ func TestBaseToUsrPass(t *testing.T) { s: data{ "username": "default-user", "password": "default-pass", - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "kv2-user", "password": "kv2-pass", }, @@ -188,7 +188,7 @@ func TestBaseToUsrPass(t *testing.T) { given: args{ s: data{ "username": "default-user", - "testing": map[string]interface{}{ + "testing": map[string]any{ "my-password": "secret", }, }, @@ -202,7 +202,7 @@ func TestBaseToUsrPass(t *testing.T) { given: args{ s: data{ "password": "default-pass", - "testing": map[string]interface{}{ + "testing": map[string]any{ "a-user-name": "me", }, }, @@ -215,12 +215,12 @@ func TestBaseToUsrPass(t *testing.T) { name: "both-json-pointer", given: args{ s: data{ - "first-path": map[string]interface{}{ - "deeper-path": map[string]interface{}{ + "first-path": map[string]any{ + "deeper-path": map[string]any{ "my-special-user": "you-found-me", }, }, - "testing": map[string]interface{}{ + "testing": map[string]any{ "password": "secret", }, }, diff --git a/internal/credential/vault/jobs.go b/internal/credential/vault/jobs.go index 7a035309e9..1ee282df96 100644 --- a/internal/credential/vault/jobs.go +++ b/internal/credential/vault/jobs.go @@ -143,7 +143,7 @@ func (r *TokenRenewalJob) Run(ctx context.Context) error { // Fetch all tokens that will reach their renewal point within the renewalWindow. // This is done to avoid constantly scheduling the token renewal job when there are multiple tokens // set to renew in sequence. - err := r.reader.SearchWhere(ctx, &ps, `token_renewal_time < wt_add_seconds_to_now(?)`, []interface{}{renewalWindow.Seconds()}, db.WithLimit(r.limit)) + err := r.reader.SearchWhere(ctx, &ps, `token_renewal_time < wt_add_seconds_to_now(?)`, []any{renewalWindow.Seconds()}, db.WithLimit(r.limit)) if err != nil { return errors.Wrap(ctx, err, op) } @@ -206,7 +206,7 @@ func (r *TokenRenewalJob) renewToken(ctx context.Context, s *clientStore) error } // Set credentials associated with this token to expired as Vault will already cascade delete them - _, err = r.writer.Exec(ctx, updateCredentialStatusByTokenQuery, []interface{}{ExpiredCredential, token.TokenHmac}) + _, err = r.writer.Exec(ctx, updateCredentialStatusByTokenQuery, []any{ExpiredCredential, token.TokenHmac}) if err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg("error updating credentials to revoked after revoking token")) } @@ -439,7 +439,7 @@ func (r *TokenRevocationJob) revokeToken(ctx context.Context, s *clientStore) er } // Set credentials associated with this token to revoked as Vault will already cascade revoke them - _, err = r.writer.Exec(ctx, updateCredentialStatusByTokenQuery, []interface{}{RevokedCredential, token.TokenHmac}) + _, err = r.writer.Exec(ctx, updateCredentialStatusByTokenQuery, []any{RevokedCredential, token.TokenHmac}) if err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg("error updating credentials to revoked after revoking token")) } @@ -531,7 +531,7 @@ func (r *CredentialRenewalJob) Run(ctx context.Context) error { // Fetch all active credentials that will reach their renewal point within the renewalWindow. // This is done to avoid constantly scheduling the credential renewal job when there are // multiple credentials set to renew in sequence. - err := r.reader.SearchWhere(ctx, &creds, `renewal_time < wt_add_seconds_to_now(?) and status = ?`, []interface{}{renewalWindow.Seconds(), ActiveCredential}, db.WithLimit(r.limit)) + err := r.reader.SearchWhere(ctx, &creds, `renewal_time < wt_add_seconds_to_now(?) and status = ?`, []any{renewalWindow.Seconds(), ActiveCredential}, db.WithLimit(r.limit)) if err != nil { return errors.Wrap(ctx, err, op) } @@ -691,7 +691,7 @@ func (r *CredentialRevocationJob) Run(ctx context.Context) error { } var creds []*privateCredential - err := r.reader.SearchWhere(ctx, &creds, "status = ?", []interface{}{RevokeCredential}, db.WithLimit(r.limit)) + err := r.reader.SearchWhere(ctx, &creds, "status = ?", []any{RevokeCredential}, db.WithLimit(r.limit)) if err != nil { return errors.Wrap(ctx, err, op) } @@ -835,7 +835,7 @@ func (r *CredentialStoreCleanupJob) Run(ctx context.Context) error { // operations. Push cleanup to the database once bulk // operations are added. var stores []*CredentialStore - err := r.reader.SearchWhere(ctx, &stores, credStoreCleanupWhereClause, []interface{}{RevokeToken}, db.WithLimit(r.limit)) + err := r.reader.SearchWhere(ctx, &stores, credStoreCleanupWhereClause, []any{RevokeToken}, db.WithLimit(r.limit)) if err != nil { return errors.Wrap(ctx, err, op) } diff --git a/internal/credential/vault/jobs_test.go b/internal/credential/vault/jobs_test.go index 10c6d3fe9a..4810f6ec38 100644 --- a/internal/credential/vault/jobs_test.go +++ b/internal/credential/vault/jobs_test.go @@ -56,7 +56,7 @@ func testVaultToken(t *testing.T, require.NoError(inToken.encrypt(context.Background(), databaseWrapper)) query := insertTokenQuery - queryValues := []interface{}{ + queryValues := []any{ sql.Named("1", inToken.TokenHmac), sql.Named("2", inToken.CtToken), sql.Named("3", inToken.StoreId), @@ -81,7 +81,7 @@ func testVaultToken(t *testing.T, require.NoError(err) outToken := allocToken() - require.NoError(rw.LookupWhere(context.Background(), &outToken, "token_hmac = ?", []interface{}{inToken.TokenHmac})) + require.NoError(rw.LookupWhere(context.Background(), &outToken, "token_hmac = ?", []any{inToken.TokenHmac})) require.NoError(outToken.decrypt(context.Background(), databaseWrapper)) return outToken @@ -117,7 +117,7 @@ func testVaultCred(t *testing.T, require.NoError(err) query := insertCredentialWithExpirationQuery - queryValues := []interface{}{ + queryValues := []any{ sql.Named("public_id", id), sql.Named("library_id", cl.GetPublicId()), sql.Named("session_id", sess.GetPublicId()), @@ -144,7 +144,7 @@ func testVaultCred(t *testing.T, assert.NoError(err) outCred := allocCredential() - require.NoError(rw.LookupWhere(context.Background(), &outCred, "public_id = ?", []interface{}{id})) + require.NoError(rw.LookupWhere(context.Background(), &outCred, "public_id = ?", []any{id})) return secret, outCred } @@ -300,7 +300,7 @@ func TestTokenRenewalJob_RunLimits(t *testing.T) { } // inserting new tokens moves the current token to a maintaining state, move it back to current and set expiration time - numRows, err := rw.Exec(context.Background(), testUpdateTokenStatusExpirationQuery, []interface{}{CurrentToken, time.Minute.Seconds(), cs.outputToken.TokenHmac}) + numRows, err := rw.Exec(context.Background(), testUpdateTokenStatusExpirationQuery, []any{CurrentToken, time.Minute.Seconds(), cs.outputToken.TokenHmac}) require.NoError(err) assert.Equal(1, numRows) @@ -357,12 +357,12 @@ func TestTokenRenewalJob_Run(t *testing.T) { expiredToken := testVaultToken(t, conn, wrapper, v, cs, ExpiredToken, time.Minute) // inserting new tokens moves the current token to a maintaining state, move it back to current and set expiration time - count, err := rw.Exec(context.Background(), testUpdateTokenStatusExpirationQuery, []interface{}{CurrentToken, time.Minute.Seconds(), cs.outputToken.TokenHmac}) + count, err := rw.Exec(context.Background(), testUpdateTokenStatusExpirationQuery, []any{CurrentToken, time.Minute.Seconds(), cs.outputToken.TokenHmac}) require.NoError(err) assert.Equal(1, count) currentToken := allocToken() - require.NoError(rw.LookupWhere(context.Background(), ¤tToken, "token_hmac = ?", []interface{}{cs.outputToken.TokenHmac})) + require.NoError(rw.LookupWhere(context.Background(), ¤tToken, "token_hmac = ?", []any{cs.outputToken.TokenHmac})) databaseWrapper, err := kmsCache.GetWrapper(context.Background(), cs.ProjectId, kms.KeyPurposeDatabase) require.NoError(err) require.NoError(currentToken.decrypt(context.Background(), databaseWrapper)) @@ -412,18 +412,18 @@ func TestTokenRenewalJob_Run(t *testing.T) { // Verify current and maintaining tokens were renewed in repo repoToken := allocToken() - require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{currentToken.TokenHmac})) + require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{currentToken.TokenHmac})) assert.True(currentToken.GetExpirationTime().AsTime().Before(repoToken.GetExpirationTime().AsTime())) repoToken = allocToken() - require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{maintainToken.TokenHmac})) + require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{maintainToken.TokenHmac})) assert.True(maintainToken.GetExpirationTime().AsTime().Before(repoToken.GetExpirationTime().AsTime())) // Verify revoked and expired tokens were not renewed in the repo repoToken = allocToken() - require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{revokedToken.TokenHmac})) + require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{revokedToken.TokenHmac})) assert.Equal(revokedToken.GetExpirationTime().AsTime(), repoToken.GetExpirationTime().AsTime()) repoToken = allocToken() - require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{expiredToken.TokenHmac})) + require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{expiredToken.TokenHmac})) assert.Equal(expiredToken.GetExpirationTime().AsTime(), repoToken.GetExpirationTime().AsTime()) } @@ -467,7 +467,7 @@ func TestTokenRenewalJob_RunExpired(t *testing.T) { // Verify token was expired in repo token := allocToken() - require.NoError(rw.LookupWhere(context.Background(), &token, "store_id = ?", []interface{}{cs.GetPublicId()})) + require.NoError(rw.LookupWhere(context.Background(), &token, "store_id = ?", []any{cs.GetPublicId()})) assert.Equal(string(ExpiredToken), token.Status) // Updating the credential store with a token that will expire before the job scheduler can run should return an error @@ -601,7 +601,7 @@ func TestTokenRenewalJob_NextRunIn(t *testing.T) { } // inserting new tokens moves the current token to a maintaining state, move it back to current and set expiration time - count, err := rw.Exec(context.Background(), testUpdateTokenStatusExpirationQuery, []interface{}{CurrentToken, tt.currentTokenExp.Seconds(), cs.outputToken.TokenHmac}) + count, err := rw.Exec(context.Background(), testUpdateTokenStatusExpirationQuery, []any{CurrentToken, tt.currentTokenExp.Seconds(), cs.outputToken.TokenHmac}) require.NoError(err) assert.Equal(1, count) } @@ -772,7 +772,7 @@ func TestTokenRevocationJob_RunLimits(t *testing.T) { } // inserting new tokens moves the current token to a maintaining state, move it back to current and set expiration time - numRows, err := rw.Exec(context.Background(), testUpdateTokenStatusExpirationQuery, []interface{}{CurrentToken, time.Minute.Seconds(), cs.outputToken.TokenHmac}) + numRows, err := rw.Exec(context.Background(), testUpdateTokenStatusExpirationQuery, []any{CurrentToken, time.Minute.Seconds(), cs.outputToken.TokenHmac}) require.NoError(err) assert.Equal(1, numRows) @@ -834,7 +834,7 @@ func TestTokenRevocationJob_Run(t *testing.T) { revokeToken := testVaultToken(t, conn, wrapper, v, cs, RevokeToken, 5*time.Minute) // inserting new tokens moves the current token to a maintaining state, move it back to current and set expiration time - count, err := rw.Exec(context.Background(), testUpdateTokenStatusExpirationQuery, []interface{}{CurrentToken, (5 * time.Minute).Seconds(), cs.outputToken.TokenHmac}) + count, err := rw.Exec(context.Background(), testUpdateTokenStatusExpirationQuery, []any{CurrentToken, (5 * time.Minute).Seconds(), cs.outputToken.TokenHmac}) require.NoError(err) assert.Equal(1, count) @@ -882,7 +882,7 @@ func TestTokenRevocationJob_Run(t *testing.T) { // Verify noCredsToken was set to revoked in repo repoToken := allocToken() - require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{noCredsToken.TokenHmac})) + require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{noCredsToken.TokenHmac})) assert.Equal(string(RevokedToken), repoToken.Status) // Verify revokeToken was revoked in vault @@ -890,7 +890,7 @@ func TestTokenRevocationJob_Run(t *testing.T) { // Verify revokeToken was set to revoked in repo repoToken = allocToken() - require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{revokeToken.TokenHmac})) + require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{revokeToken.TokenHmac})) assert.Equal(string(RevokedToken), repoToken.Status) // Verify revokeCred attached to revokeToken were marked as revoked @@ -919,7 +919,7 @@ func TestTokenRevocationJob_Run(t *testing.T) { // Verify credsToken was set to revoked in repo repoToken = allocToken() - require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{credsToken.TokenHmac})) + require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{credsToken.TokenHmac})) assert.Equal(string(RevokedToken), repoToken.Status) err = r.Run(context.Background()) @@ -1177,7 +1177,7 @@ func TestCredentialRenewalJob_Run(t *testing.T) { }) csToken := allocToken() - require.NoError(rw.LookupWhere(context.Background(), &csToken, "token_hmac = ?", []interface{}{cs.outputToken.TokenHmac})) + require.NoError(rw.LookupWhere(context.Background(), &csToken, "token_hmac = ?", []any{cs.outputToken.TokenHmac})) credRenewal, err := newCredentialRenewalJob(rw, rw, kmsCache) require.NoError(err) @@ -1287,7 +1287,7 @@ func TestCredentialRenewalJob_RunExpired(t *testing.T) { }) repoToken := allocToken() - require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{cs.outputToken.TokenHmac})) + require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{cs.outputToken.TokenHmac})) credRenewal, err := newCredentialRenewalJob(rw, rw, kmsCache) require.NoError(err) @@ -1608,7 +1608,7 @@ func TestCredentialRevocationJob_RunLimits(t *testing.T) { }) repoToken := allocToken() - require.NoError(t, rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{cs.outputToken.TokenHmac})) + require.NoError(t, rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{cs.outputToken.TokenHmac})) count := 10 tests := []struct { @@ -1722,7 +1722,7 @@ func TestCredentialRevocationJob_Run(t *testing.T) { }) repoToken := allocToken() - require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{cs.outputToken.TokenHmac})) + require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{cs.outputToken.TokenHmac})) r, err := newCredentialRevocationJob(rw, rw, kmsCache) require.NoError(err) @@ -1816,7 +1816,7 @@ func TestCredentialRevocationJob_RunDeleted(t *testing.T) { }) repoToken := allocToken() - require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{cs.outputToken.TokenHmac})) + require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{cs.outputToken.TokenHmac})) r, err := newCredentialRevocationJob(rw, rw, kmsCache) require.NoError(err) @@ -1991,11 +1991,11 @@ func TestCredentialStoreCleanupJob_Run(t *testing.T) { // Get token hmac for verifications below repoToken := allocToken() - require.NoError(rw.LookupWhere(context.Background(), &repoToken, "store_id = ?", []interface{}{cs1.PublicId})) + require.NoError(rw.LookupWhere(context.Background(), &repoToken, "store_id = ?", []any{cs1.PublicId})) cs1TokenHmac := repoToken.TokenHmac repoToken = allocToken() - require.NoError(rw.LookupWhere(context.Background(), &repoToken, "store_id = ?", []interface{}{cs2.PublicId})) + require.NoError(rw.LookupWhere(context.Background(), &repoToken, "store_id = ?", []any{cs2.PublicId})) cs2TokenHmac := repoToken.TokenHmac // create second token on cs2 @@ -2029,11 +2029,11 @@ func TestCredentialStoreCleanupJob_Run(t *testing.T) { // Verify tokens have been set to revoke repoToken = allocToken() - require.NoError(rw.LookupWhere(context.Background(), &repoToken, "store_id = ?", []interface{}{cs1.PublicId})) + require.NoError(rw.LookupWhere(context.Background(), &repoToken, "store_id = ?", []any{cs1.PublicId})) assert.Equal(string(RevokeToken), repoToken.Status) repoToken = allocToken() - require.NoError(rw.LookupWhere(context.Background(), &repoToken, "store_id = ?", []interface{}{cs2.PublicId})) + require.NoError(rw.LookupWhere(context.Background(), &repoToken, "store_id = ?", []any{cs2.PublicId})) assert.Equal(string(RevokeToken), repoToken.Status) // Both soft deleted credential stores should not be cleaned up yet @@ -2042,7 +2042,7 @@ func TestCredentialStoreCleanupJob_Run(t *testing.T) { assert.Equal(0, r.numStores) // Update cs1 token to be marked as revoked - count, err = rw.Exec(context.Background(), updateTokenStatusQuery, []interface{}{RevokedToken, cs1TokenHmac}) + count, err = rw.Exec(context.Background(), updateTokenStatusQuery, []any{RevokedToken, cs1TokenHmac}) require.NoError(err) assert.Equal(1, count) @@ -2058,7 +2058,7 @@ func TestCredentialStoreCleanupJob_Run(t *testing.T) { require.Error(err) assert.True(errors.IsNotFoundError(err)) repoToken = allocToken() - err = rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{cs1TokenHmac}) + err = rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{cs1TokenHmac}) require.Error(err) assert.True(errors.IsNotFoundError(err)) @@ -2066,11 +2066,11 @@ func TestCredentialStoreCleanupJob_Run(t *testing.T) { _, err = repo.LookupCredentialStore(context.Background(), cs2.PublicId) require.NoError(err) repoToken = allocToken() - err = rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{cs2TokenHmac}) + err = rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{cs2TokenHmac}) require.NoError(err) // Update cs2 token expiration time - count, err = rw.Exec(context.Background(), "update credential_vault_token set expiration_time = now() where token_hmac = ?;", []interface{}{cs2TokenHmac}) + count, err = rw.Exec(context.Background(), "update credential_vault_token set expiration_time = now() where token_hmac = ?;", []any{cs2TokenHmac}) require.NoError(err) assert.Equal(1, count) @@ -2083,11 +2083,11 @@ func TestCredentialStoreCleanupJob_Run(t *testing.T) { _, err = repo.LookupCredentialStore(context.Background(), cs2.PublicId) require.NoError(err) repoToken = allocToken() - err = rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{cs2TokenHmac}) + err = rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{cs2TokenHmac}) require.NoError(err) // set secondToken with an expired status - count, err = rw.Exec(context.Background(), updateTokenStatusQuery, []interface{}{ExpiredToken, secondToken.TokenHmac}) + count, err = rw.Exec(context.Background(), updateTokenStatusQuery, []any{ExpiredToken, secondToken.TokenHmac}) require.NoError(err) assert.Equal(1, count) @@ -2103,10 +2103,10 @@ func TestCredentialStoreCleanupJob_Run(t *testing.T) { require.Error(err) assert.True(errors.IsNotFoundError(err)) repoToken = allocToken() - err = rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{cs2TokenHmac}) + err = rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{cs2TokenHmac}) require.Error(err) assert.True(errors.IsNotFoundError(err)) - err = rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{secondToken.TokenHmac}) + err = rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{secondToken.TokenHmac}) require.Error(err) assert.True(errors.IsNotFoundError(err)) } @@ -2217,7 +2217,7 @@ func TestCredentialCleanupJob_Run(t *testing.T) { }) repoToken := allocToken() - require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []interface{}{cs.outputToken.TokenHmac})) + require.NoError(rw.LookupWhere(context.Background(), &repoToken, "token_hmac = ?", []any{cs.outputToken.TokenHmac})) r, err := newCredentialCleanupJob(rw) require.NoError(err) diff --git a/internal/credential/vault/private_library.go b/internal/credential/vault/private_library.go index 700a299be1..d6c57311cf 100644 --- a/internal/credential/vault/private_library.go +++ b/internal/credential/vault/private_library.go @@ -25,7 +25,7 @@ type baseCred struct { *Credential lib *issueCredentialLibrary - secretData map[string]interface{} + secretData map[string]any } func (bc *baseCred) Secret() credential.SecretData { return bc.secretData } @@ -283,8 +283,8 @@ func (pl *issueCredentialLibrary) client(ctx context.Context) (vaultClient, erro type dynamicCred interface { credential.Dynamic getExpiration() time.Duration - insertQuery() (query string, queryValues []interface{}) - updateSessionQuery(purpose credential.Purpose) (query string, queryValues []interface{}) + insertQuery() (query string, queryValues []any) + updateSessionQuery(purpose credential.Purpose) (query string, queryValues []any) } // retrieveCredential retrieves a dynamic credential from Vault for the @@ -359,7 +359,7 @@ func (r *Repository) getIssueCredLibraries(ctx context.Context, requests []crede query := fmt.Sprintf(selectLibrariesQuery, inClause) - var params []interface{} + var params []any for idx, v := range libIds { params = append(params, sql.Named(fmt.Sprintf("%d", idx+1), v)) } diff --git a/internal/credential/vault/private_library_test.go b/internal/credential/vault/private_library_test.go index 8e2bf1a310..fc156232bc 100644 --- a/internal/credential/vault/private_library_test.go +++ b/internal/credential/vault/private_library_test.go @@ -426,7 +426,7 @@ func TestBaseToUsrPass(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.UsernamePasswordType), }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "password": "my-password", }, }, @@ -438,7 +438,7 @@ func TestBaseToUsrPass(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.UsernamePasswordType), }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "username": "my-username", }, }, @@ -450,7 +450,7 @@ func TestBaseToUsrPass(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.UsernamePasswordType), }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "username": "my-username", "password": "my-password", }, @@ -468,7 +468,7 @@ func TestBaseToUsrPass(t *testing.T) { UsernameAttribute: "test-username", PasswordAttribute: "test-password", }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "username": "default-username", "password": "default-password", "test-username": "override-username", @@ -487,7 +487,7 @@ func TestBaseToUsrPass(t *testing.T) { CredType: string(credential.UsernamePasswordType), PasswordAttribute: "test-password", }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "username": "default-username", "password": "default-password", "test-username": "override-username", @@ -506,7 +506,7 @@ func TestBaseToUsrPass(t *testing.T) { CredType: string(credential.UsernamePasswordType), UsernameAttribute: "test-username", }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "username": "default-username", "password": "default-password", "test-username": "override-username", @@ -525,7 +525,7 @@ func TestBaseToUsrPass(t *testing.T) { CredType: string(credential.UsernamePasswordType), UsernameAttribute: "missing-username", }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "username": "default-username", "password": "default-password", "test-username": "override-username", @@ -541,7 +541,7 @@ func TestBaseToUsrPass(t *testing.T) { CredType: string(credential.UsernamePasswordType), UsernameAttribute: "missing-password", }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "username": "default-username", "password": "default-password", "test-username": "override-username", @@ -556,8 +556,8 @@ func TestBaseToUsrPass(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.UsernamePasswordType), }, - secretData: map[string]interface{}{ - "data": map[string]interface{}{ + secretData: map[string]any{ + "data": map[string]any{ "username": "my-username", "password": "my-password", }, @@ -571,8 +571,8 @@ func TestBaseToUsrPass(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.UsernamePasswordType), }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, + secretData: map[string]any{ + "metadata": map[string]any{}, }, }, wantErr: errors.VaultInvalidCredentialMapping, @@ -583,9 +583,9 @@ func TestBaseToUsrPass(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.UsernamePasswordType), }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + secretData: map[string]any{ + "metadata": map[string]any{}, + "data": map[string]any{ "password": "my-password", }, }, @@ -598,9 +598,9 @@ func TestBaseToUsrPass(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.UsernamePasswordType), }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + secretData: map[string]any{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "my-username", }, }, @@ -613,9 +613,9 @@ func TestBaseToUsrPass(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.UsernamePasswordType), }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "metadata": "hello", - "data": map[string]interface{}{ + "data": map[string]any{ "username": "my-username", "password": "my-password", }, @@ -629,8 +629,8 @@ func TestBaseToUsrPass(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.UsernamePasswordType), }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, + secretData: map[string]any{ + "metadata": map[string]any{}, "data": "hello", }, }, @@ -642,10 +642,10 @@ func TestBaseToUsrPass(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.UsernamePasswordType), }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "bad-field": "hello", - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "my-username", "password": "my-password", }, @@ -659,9 +659,9 @@ func TestBaseToUsrPass(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.UsernamePasswordType), }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + secretData: map[string]any{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "my-username", "password": "my-password", }, @@ -680,9 +680,9 @@ func TestBaseToUsrPass(t *testing.T) { UsernameAttribute: "test-username", PasswordAttribute: "test-password", }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + secretData: map[string]any{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "default-username", "password": "default-password", "test-username": "override-username", @@ -702,9 +702,9 @@ func TestBaseToUsrPass(t *testing.T) { CredType: string(credential.UsernamePasswordType), PasswordAttribute: "test-password", }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + secretData: map[string]any{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "default-username", "password": "default-password", "test-username": "override-username", @@ -724,9 +724,9 @@ func TestBaseToUsrPass(t *testing.T) { CredType: string(credential.UsernamePasswordType), UsernameAttribute: "test-username", }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + secretData: map[string]any{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "default-username", "password": "default-password", "test-username": "override-username", @@ -791,7 +791,7 @@ func TestBaseToSshPriKey(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.SshPrivateKeyType), }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "private_key": "my-pk", }, }, @@ -803,7 +803,7 @@ func TestBaseToSshPriKey(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.SshPrivateKeyType), }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "username": "my-username", }, }, @@ -815,7 +815,7 @@ func TestBaseToSshPriKey(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.SshPrivateKeyType), }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "username": "my-username", "private_key": "my-pk", }, @@ -831,7 +831,7 @@ func TestBaseToSshPriKey(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.SshPrivateKeyType), }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "username": "my-username", "private_key": "my-pk", "private_key_passphrase": "my-pass", @@ -851,7 +851,7 @@ func TestBaseToSshPriKey(t *testing.T) { UsernameAttribute: "test-username", PrivateKeyAttribute: "test-pk", }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "username": "default-username", "private_key": "default-pk", "test-username": "override-username", @@ -872,7 +872,7 @@ func TestBaseToSshPriKey(t *testing.T) { PrivateKeyAttribute: "test-pk", PrivateKeyPassphraseAttribute: "test-pass", }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "username": "default-username", "private_key": "default-pk", "passphrase": "default-pass", @@ -894,7 +894,7 @@ func TestBaseToSshPriKey(t *testing.T) { CredType: string(credential.SshPrivateKeyType), PrivateKeyAttribute: "test-pk", }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "username": "default-username", "private_key": "default-pk", "test-username": "override-username", @@ -913,7 +913,7 @@ func TestBaseToSshPriKey(t *testing.T) { CredType: string(credential.SshPrivateKeyType), UsernameAttribute: "test-username", }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "username": "default-username", "private_key": "default-pk", "test-username": "override-username", @@ -932,7 +932,7 @@ func TestBaseToSshPriKey(t *testing.T) { CredType: string(credential.SshPrivateKeyType), UsernameAttribute: "missing-username", }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "username": "default-username", "private_key": "default-pk", "test-username": "override-username", @@ -948,7 +948,7 @@ func TestBaseToSshPriKey(t *testing.T) { CredType: string(credential.SshPrivateKeyType), UsernameAttribute: "missing-pk", }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "username": "default-username", "private_key": "default-pk", "test-username": "override-username", @@ -963,8 +963,8 @@ func TestBaseToSshPriKey(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.SshPrivateKeyType), }, - secretData: map[string]interface{}{ - "data": map[string]interface{}{ + secretData: map[string]any{ + "data": map[string]any{ "username": "default-username", "private_key": "default-pk", }, @@ -978,8 +978,8 @@ func TestBaseToSshPriKey(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.SshPrivateKeyType), }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, + secretData: map[string]any{ + "metadata": map[string]any{}, }, }, wantErr: errors.VaultInvalidCredentialMapping, @@ -990,9 +990,9 @@ func TestBaseToSshPriKey(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.SshPrivateKeyType), }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + secretData: map[string]any{ + "metadata": map[string]any{}, + "data": map[string]any{ "private_key": "default-pk", }, }, @@ -1005,9 +1005,9 @@ func TestBaseToSshPriKey(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.SshPrivateKeyType), }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + secretData: map[string]any{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "default-username", }, }, @@ -1020,9 +1020,9 @@ func TestBaseToSshPriKey(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.SshPrivateKeyType), }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "metadata": "hello", - "data": map[string]interface{}{ + "data": map[string]any{ "username": "default-username", "private_key": "default-pk", }, @@ -1036,8 +1036,8 @@ func TestBaseToSshPriKey(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.SshPrivateKeyType), }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, + secretData: map[string]any{ + "metadata": map[string]any{}, "data": "hello", }, }, @@ -1049,10 +1049,10 @@ func TestBaseToSshPriKey(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.SshPrivateKeyType), }, - secretData: map[string]interface{}{ + secretData: map[string]any{ "bad-field": "hello", - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "default-username", "private_key": "default-pk", }, @@ -1066,9 +1066,9 @@ func TestBaseToSshPriKey(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.SshPrivateKeyType), }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + secretData: map[string]any{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "default-username", "private_key": "default-pk", }, @@ -1085,9 +1085,9 @@ func TestBaseToSshPriKey(t *testing.T) { lib: &issueCredentialLibrary{ CredType: string(credential.SshPrivateKeyType), }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + secretData: map[string]any{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "default-username", "private_key": "default-pk", "private_key_passphrase": "default-pass", @@ -1108,9 +1108,9 @@ func TestBaseToSshPriKey(t *testing.T) { UsernameAttribute: "test-username", PrivateKeyAttribute: "test-pk", }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + secretData: map[string]any{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "default-username", "private_key": "default-pk", "test-username": "override-username", @@ -1132,9 +1132,9 @@ func TestBaseToSshPriKey(t *testing.T) { PrivateKeyAttribute: "test-pk", PrivateKeyPassphraseAttribute: "test-pass", }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + secretData: map[string]any{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "default-username", "private_key": "default-pk", "passphrase": "default-pass", @@ -1157,9 +1157,9 @@ func TestBaseToSshPriKey(t *testing.T) { CredType: string(credential.SshPrivateKeyType), PrivateKeyAttribute: "test-pk", }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + secretData: map[string]any{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "default-username", "private_key": "default-pk", "test-username": "override-username", @@ -1179,9 +1179,9 @@ func TestBaseToSshPriKey(t *testing.T) { CredType: string(credential.SshPrivateKeyType), UsernameAttribute: "test-username", }, - secretData: map[string]interface{}{ - "metadata": map[string]interface{}{}, - "data": map[string]interface{}{ + secretData: map[string]any{ + "metadata": map[string]any{}, + "data": map[string]any{ "username": "default-username", "private_key": "default-pk", "test-username": "override-username", diff --git a/internal/credential/vault/private_store.go b/internal/credential/vault/private_store.go index 311103dc68..21086edbdd 100644 --- a/internal/credential/vault/private_store.go +++ b/internal/credential/vault/private_store.go @@ -17,7 +17,7 @@ func (r *Repository) lookupClientStore(ctx context.Context, publicId string) (*c return nil, errors.New(ctx, errors.InvalidParameter, op, "no public id") } ps := allocClientStore() - if err := r.reader.LookupWhere(ctx, &ps, "public_id = ?", []interface{}{publicId}); err != nil { + if err := r.reader.LookupWhere(ctx, &ps, "public_id = ?", []any{publicId}); err != nil { if errors.IsNotFoundError(err) { return nil, nil } diff --git a/internal/credential/vault/repository_credential_library.go b/internal/credential/vault/repository_credential_library.go index 7be4bcd0d5..14b6457341 100644 --- a/internal/credential/vault/repository_credential_library.go +++ b/internal/credential/vault/repository_credential_library.go @@ -158,7 +158,7 @@ func (r *Repository) UpdateCredentialLibrary(ctx context.Context, projectId stri } var dbMask, nullFields []string dbMask, nullFields = dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ nameField: l.Name, descriptionField: l.Description, vaultPathField: l.VaultPath, @@ -463,7 +463,7 @@ func (r *Repository) ListCredentialLibraries(ctx context.Context, storeId string limit = opts.withLimit } var libs []*CredentialLibrary - err := r.reader.SearchWhere(ctx, &libs, "store_id = ?", []interface{}{storeId}, db.WithLimit(limit)) + err := r.reader.SearchWhere(ctx, &libs, "store_id = ?", []any{storeId}, db.WithLimit(limit)) if err != nil { return nil, errors.Wrap(ctx, err, op) } diff --git a/internal/credential/vault/repository_credential_library_test.go b/internal/credential/vault/repository_credential_library_test.go index 5a0418f5c6..2c6996508e 100644 --- a/internal/credential/vault/repository_credential_library_test.go +++ b/internal/credential/vault/repository_credential_library_test.go @@ -476,7 +476,7 @@ func TestRepository_CreateCredentialLibrary(t *testing.T) { // verify it was persisted in the database override := allocUsernamePasswordOverride() - assert.NoError(rw.LookupWhere(ctx, &override, "library_id = ?", []interface{}{got.GetPublicId()})) + assert.NoError(rw.LookupWhere(ctx, &override, "library_id = ?", []any{got.GetPublicId()})) case *SshPrivateKeyOverride: g, ok := got.MappingOverride.(*SshPrivateKeyOverride) @@ -487,7 +487,7 @@ func TestRepository_CreateCredentialLibrary(t *testing.T) { // verify it was persisted in the database override := allocSshPrivateKeyOverride() - assert.NoError(rw.LookupWhere(ctx, &override, "library_id = ?", []interface{}{got.GetPublicId()})) + assert.NoError(rw.LookupWhere(ctx, &override, "library_id = ?", []any{got.GetPublicId()})) default: assert.Fail("Unknown mapping override") @@ -1650,7 +1650,7 @@ func TestRepository_UpdateCredentialLibrary(t *testing.T) { // Expire the credential store Vault token rows, err := rw.Exec(context.Background(), "update credential_vault_token set status = ? where token_hmac = ?", - []interface{}{ExpiredToken, cs.Token().TokenHmac}) + []any{ExpiredToken, cs.Token().TokenHmac}) require.NoError(err) require.Equal(1, rows) @@ -1709,7 +1709,7 @@ func TestRepository_LookupCredentialLibrary(t *testing.T) { csWithExpiredToken := css[1] rows, err := rw.Exec(context.Background(), "update credential_vault_token set status = ? where token_hmac = ?", - []interface{}{ExpiredToken, csWithExpiredToken.Token().TokenHmac}) + []any{ExpiredToken, csWithExpiredToken.Token().TokenHmac}) require.NoError(t, err) require.Equal(t, 1, rows) diff --git a/internal/credential/vault/repository_credential_store.go b/internal/credential/vault/repository_credential_store.go index b4166eab5b..1310c1ce10 100644 --- a/internal/credential/vault/repository_credential_store.go +++ b/internal/credential/vault/repository_credential_store.go @@ -383,7 +383,7 @@ func (r *Repository) UpdateCredentialStore(ctx context.Context, cs *CredentialSt } } dbMask, nullFields := dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ nameField: cs.Name, descriptionField: cs.Description, namespaceField: cs.Namespace, @@ -405,7 +405,7 @@ func (r *Repository) UpdateCredentialStore(ctx context.Context, cs *CredentialSt clientCertKey = cs.ClientCertificate().GetCertificateKey() } certDbMask, certNullFields := dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ certificateField: clientCert, certificateKeyField: clientCertKey, }, @@ -657,7 +657,7 @@ func (r *Repository) ListCredentialStores(ctx context.Context, projectIds []stri limit = opts.withLimit } var credentialStores []*listLookupStore - err := r.reader.SearchWhere(ctx, &credentialStores, "project_id in (?)", []interface{}{projectIds}, db.WithLimit(limit)) + err := r.reader.SearchWhere(ctx, &credentialStores, "project_id in (?)", []any{projectIds}, db.WithLimit(limit)) if err != nil { return nil, errors.Wrap(ctx, err, op) } diff --git a/internal/credential/vault/repository_credential_store_test.go b/internal/credential/vault/repository_credential_store_test.go index 824c9227a5..10f65be64a 100644 --- a/internal/credential/vault/repository_credential_store_test.go +++ b/internal/credential/vault/repository_credential_store_test.go @@ -217,11 +217,11 @@ func TestRepository_CreateCredentialStoreNonResource(t *testing.T) { assert.NoError(db.TestVerifyOplog(t, rw, got.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second))) outToken := allocToken() - assert.NoError(rw.LookupWhere(ctx, &outToken, "store_id = ?", []interface{}{got.PublicId})) + assert.NoError(rw.LookupWhere(ctx, &outToken, "store_id = ?", []any{got.PublicId})) if tt.tls == TestClientTLS { outClientCert := allocClientCertificate() - assert.NoError(rw.LookupWhere(ctx, &outClientCert, "store_id = ?", []interface{}{got.PublicId})) + assert.NoError(rw.LookupWhere(ctx, &outClientCert, "store_id = ?", []any{got.PublicId})) } }) } @@ -248,7 +248,7 @@ func TestRepository_LookupCredentialStore(t *testing.T) { rows, err = rw.Exec(context.Background(), "update credential_vault_token set status = ? where token_hmac = ?", - []interface{}{ExpiredToken, csWithExpiredToken.Token().TokenHmac}) + []any{ExpiredToken, csWithExpiredToken.Token().TokenHmac}) require.NoError(t, err) require.Equal(t, 1, rows) @@ -1054,7 +1054,7 @@ func TestRepository_UpdateCredentialStore_VaultToken(t *testing.T) { updateToken: func(ctx context.Context, tokenHmac []byte) { _, err := rw.Exec(ctx, "update credential_vault_token set status = ? where token_hmac = ?", - []interface{}{ExpiredToken, tokenHmac}) + []any{ExpiredToken, tokenHmac}) require.NoError(t, err) }, wantCount: 1, @@ -1128,7 +1128,7 @@ func TestRepository_UpdateCredentialStore_VaultToken(t *testing.T) { assert.NotNil(got) var tokens []*Token - require.NoError(rw.SearchWhere(ctx, &tokens, "store_id = ?", []interface{}{orig.GetPublicId()})) + require.NoError(rw.SearchWhere(ctx, &tokens, "store_id = ?", []any{orig.GetPublicId()})) assert.Len(tokens, 2) assert.Equal(string(tt.wantOldTokenStatus), tokens[0].Status) @@ -1314,7 +1314,7 @@ func TestRepository_ListCredentialStores_Multiple_Scopes(t *testing.T) { for _, cs := range stores { rows, err := rw.Exec(context.Background(), "update credential_vault_token set status = ? where token_hmac = ?", - []interface{}{ExpiredToken, cs.Token().TokenHmac}) + []any{ExpiredToken, cs.Token().TokenHmac}) require.NoError(err) require.Equal(1, rows) } @@ -1384,7 +1384,7 @@ update credential_vault_token ctx := context.Background() for i := 0; i < count; i++ { - rows, err := rw.Exec(ctx, query, []interface{}{storeId}) + rows, err := rw.Exec(ctx, query, []any{storeId}) require.Equal(t, 1, rows) require.NoError(t, err) tokens[storeId].revoked++ @@ -1406,7 +1406,7 @@ update credential_vault_token ctx := context.Background() for i := 0; i < count; i++ { - rows, err := rw.Exec(ctx, query, []interface{}{storeId}) + rows, err := rw.Exec(ctx, query, []any{storeId}) require.Equal(t, 1, rows) require.NoError(t, err) tokens[storeId].expired++ @@ -1585,7 +1585,7 @@ group by store_id, status; { rows, err := repo.reader.Query(ctx, "select * from credential_vault_token_renewal_revocation where token_status = $1", - []interface{}{ExpiredToken}) + []any{ExpiredToken}) require.NoError(err) defer rows.Close() assert.False(rows.Next()) @@ -1660,7 +1660,7 @@ group by store_id, status; { rows, err := repo.reader.Query(ctx, "select * from credential_vault_token_renewal_revocation where token_status = $1", - []interface{}{RevokeToken}) + []any{RevokeToken}) require.NoError(err) defer rows.Close() @@ -1707,7 +1707,7 @@ group by store_id, status; { rows, err := repo.reader.Query(ctx, "select * from credential_vault_token_renewal_revocation where token_status = $1", - []interface{}{RevokeToken}) + []any{RevokeToken}) require.NoError(err) defer rows.Close() diff --git a/internal/credential/vault/repository_credentials.go b/internal/credential/vault/repository_credentials.go index bc86681e71..33210db39a 100644 --- a/internal/credential/vault/repository_credentials.go +++ b/internal/credential/vault/repository_credentials.go @@ -103,7 +103,7 @@ func (r *Repository) Revoke(ctx context.Context, sessionId string) error { _, err := r.writer.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{}, func(_ db.Reader, w db.Writer) error { - if _, err := w.Exec(ctx, revokeCredentialsQuery, []interface{}{sessionId}); err != nil { + if _, err := w.Exec(ctx, revokeCredentialsQuery, []any{sessionId}); err != nil { return errors.Wrap(ctx, err, op) } return nil diff --git a/internal/credential/vault/repository_credentials_test.go b/internal/credential/vault/repository_credentials_test.go index 732ba5f0da..998ec15ee6 100644 --- a/internal/credential/vault/repository_credentials_test.go +++ b/internal/credential/vault/repository_credentials_test.go @@ -75,7 +75,7 @@ func TestRepository_IssueCredentials(t *testing.T) { // Set previous token to expired in the database and revoke in Vault to validate a // credential store with an expired token is correctly returned over the API num, err := rw.Exec(context.Background(), "update credential_vault_token set status = ? where store_id = ?", - []interface{}{vault.ExpiredToken, expStore.PublicId}) + []any{vault.ExpiredToken, expStore.PublicId}) require.NoError(t, err) assert.Equal(t, 1, num) v.RevokeToken(t, expToken) diff --git a/internal/credential/vault/supported.go b/internal/credential/vault/supported.go index 2bcb103ff8..90b040217c 100644 --- a/internal/credential/vault/supported.go +++ b/internal/credential/vault/supported.go @@ -302,7 +302,7 @@ func gotMountDatabase(t testing.TB, v *TestVaultServer, opt ...TestOption) *Test t.Log(connUrl) postgresConfPath := path.Join(mountPath, "config/postgresql") - postgresConfOptions := map[string]interface{}{ + postgresConfOptions := map[string]any{ "plugin_name": "postgresql-database-plugin", "connection_url": connUrl, "allowed_roles": "opened,closed", @@ -330,7 +330,7 @@ grant closed_role to "{{name}}"; ) openedRolePath := path.Join(mountPath, "roles", "opened") - openedRoleOptions := map[string]interface{}{ + openedRoleOptions := map[string]any{ "db_name": "postgresql", "creation_statements": vaultOpenedCreationStatement, } @@ -338,7 +338,7 @@ grant closed_role to "{{name}}"; require.NoError(err) closedRolePath := path.Join(mountPath, "roles", "closed") - closedRoleOptions := map[string]interface{}{ + closedRoleOptions := map[string]any{ "db_name": "postgresql", "creation_statements": vaultClosedCreationStatement, } diff --git a/internal/credential/vault/testing.go b/internal/credential/vault/testing.go index 688842b0fa..bec5232010 100644 --- a/internal/credential/vault/testing.go +++ b/internal/credential/vault/testing.go @@ -226,7 +226,7 @@ func testTokens(t testing.TB, conn *db.DB, wrapper wrapping.Wrapper, projectId, num := r.Int31() inToken := createTestToken(t, conn, wrapper, projectId, storeId, fmt.Sprintf("vault-token-%s-%d-%v", storeId, i, num), fmt.Sprintf("accessor-%s-%d-%v", storeId, i, num)) outToken := allocToken() - require.NoError(w.LookupWhere(ctx, &outToken, "token_hmac = ?", []interface{}{inToken.TokenHmac})) + require.NoError(w.LookupWhere(ctx, &outToken, "token_hmac = ?", []any{inToken.TokenHmac})) require.NoError(outToken.decrypt(ctx, databaseWrapper)) tokens = append(tokens, outToken) @@ -736,7 +736,7 @@ func (v *TestVaultServer) LookupLease(t testing.TB, leaseId string) *vault.Secre t.Helper() require := require.New(t) vc := v.client(t).cl - credData := map[string]interface{}{"lease_id": leaseId} + credData := map[string]any{"lease_id": leaseId} secret, err := vc.Logical().Write("sys/leases/lookup", credData) require.NoError(err) require.NotNil(secret) @@ -804,7 +804,7 @@ func (v *TestVaultServer) MountPKI(t testing.TB, opt ...TestOption) *vault.Secre // Generate a root CA caPath := path.Join(mountPath, "root/generate/internal") - caOptions := map[string]interface{}{ + caOptions := map[string]any{ "common_name": t.Name(), "ttl": maxTTL.String(), } @@ -814,7 +814,7 @@ func (v *TestVaultServer) MountPKI(t testing.TB, opt ...TestOption) *vault.Secre // Create default role rolePath := path.Join(mountPath, "roles", opts.roleName) - roleOptions := map[string]interface{}{ + roleOptions := map[string]any{ "allow_any_name": true, "ttl": defaultTTL.String(), } @@ -872,10 +872,10 @@ type TestVaultServer struct { serverCertBundle *testCertBundle clientCertBundle *testCertBundle - pool interface{} - vaultContainer interface{} - network interface{} - postgresContainer interface{} + pool any + vaultContainer any + network any + postgresContainer any } // NewTestVaultServer creates and returns a TestVaultServer. Some Vault diff --git a/internal/credential/vault/testing_test.go b/internal/credential/vault/testing_test.go index ed6aa83f6b..ec2e976f01 100644 --- a/internal/credential/vault/testing_test.go +++ b/internal/credential/vault/testing_test.go @@ -347,7 +347,7 @@ func TestTestVaultServer_MountPKI(t *testing.T) { vc.SetToken(token) certPath := path.Join("pki", "issue", "boundary") - certOptions := map[string]interface{}{ + certOptions := map[string]any{ "common_name": "boundary.com", } certSecret, err := vc.Logical().Write(certPath, certOptions) @@ -378,7 +378,7 @@ func TestTestVaultServer_MountPKI(t *testing.T) { vc.SetToken(token) certPath := path.Join("gary", "issue", "boundary") - certOptions := map[string]interface{}{ + certOptions := map[string]any{ "common_name": "boundary.com", } certSecret, err := vc.Logical().Write(certPath, certOptions) @@ -409,7 +409,7 @@ func TestTestVaultServer_MountPKI(t *testing.T) { vc.SetToken(token) certPath := path.Join("pki", "issue", "gary") - certOptions := map[string]interface{}{ + certOptions := map[string]any{ "common_name": "boundary.com", } certSecret, err := vc.Logical().Write(certPath, certOptions) @@ -612,7 +612,7 @@ func TestTestVaultServer_CreateKVSecret(t *testing.T) { require.NotNil(got.Data) require.NotNil(got.Data["data"]) - gotData, ok := got.Data["data"].(map[string]interface{}) + gotData, ok := got.Data["data"].(map[string]any) require.True(ok) require.NotNil(gotData["foo"]) diff --git a/internal/credential/vault/vault_token.go b/internal/credential/vault/vault_token.go index 8729816989..f1687f166b 100644 --- a/internal/credential/vault/vault_token.go +++ b/internal/credential/vault/vault_token.go @@ -136,11 +136,11 @@ func (t *Token) decrypt(ctx context.Context, cipher wrapping.Wrapper) error { return nil } -func (t *Token) insertQuery() (query string, queryValues []interface{}) { +func (t *Token) insertQuery() (query string, queryValues []any) { query = insertTokenQuery exp := int(t.expiration.Round(time.Second).Seconds()) - queryValues = []interface{}{ + queryValues = []any{ sql.Named("1", t.TokenHmac), sql.Named("2", t.CtToken), sql.Named("3", t.StoreId), @@ -152,21 +152,21 @@ func (t *Token) insertQuery() (query string, queryValues []interface{}) { return } -func (t *Token) updateStatusQuery(status TokenStatus) (query string, queryValues []interface{}) { +func (t *Token) updateStatusQuery(status TokenStatus) (query string, queryValues []any) { query = updateTokenStatusQuery - queryValues = []interface{}{ + queryValues = []any{ status, t.TokenHmac, } return } -func (t *Token) updateExpirationQuery() (query string, queryValues []interface{}) { +func (t *Token) updateExpirationQuery() (query string, queryValues []any) { query = updateTokenExpirationQuery exp := int(t.expiration.Round(time.Second).Seconds()) - queryValues = []interface{}{ + queryValues = []any{ exp, t.TokenHmac, } diff --git a/internal/daemon/cluster/handlers/worker_service.go b/internal/daemon/cluster/handlers/worker_service.go index 9825daadab..b1a6cabd69 100644 --- a/internal/daemon/cluster/handlers/worker_service.go +++ b/internal/daemon/cluster/handlers/worker_service.go @@ -293,7 +293,7 @@ func (ws *workerServiceServer) LookupSession(ctx context.Context, req *pbs.Looku event.WriteError(ctx, op, err, event.WithInfoMsg("error creating worker filter evaluator", "worker_id", req.WorkerId)) return &pbs.LookupSessionResponse{}, status.Errorf(codes.Internal, "Error creating worker filter evaluator: %v", err) } - filterInput := map[string]interface{}{ + filterInput := map[string]any{ "name": w.GetName(), "tags": tagMap, } diff --git a/internal/daemon/common/handler_test.go b/internal/daemon/common/handler_test.go index 02b97f8e31..88213c74e6 100644 --- a/internal/daemon/common/handler_test.go +++ b/internal/daemon/common/handler_test.go @@ -302,13 +302,13 @@ func Test_WrapWithEventsHandler(t *testing.T) { info := event.RequestInfo{ Method: "GET", Path: "/greeting", - Id: got.Data.(map[string]interface{})["request_info"].(map[string]interface{})["id"].(string), + Id: got.Data.(map[string]any)["request_info"].(map[string]any)["id"].(string), } - hdr := map[string]interface{}{ + hdr := map[string]any{ "status": http.StatusTeapot, - "start": got.Data.(map[string]interface{})["start"].(string), - "stop": got.Data.(map[string]interface{})["stop"].(string), - "latency-ms": got.Data.(map[string]interface{})["latency-ms"].(float64), + "start": got.Data.(map[string]any)["start"].(string), + "stop": got.Data.(map[string]any)["stop"].(string), + "latency-ms": got.Data.(map[string]any)["latency-ms"].(float64), } wantJson := testJson(t, event.ObservationType, &info, event.Op(tt.name), got, hdr, nil) assert.JSONEq(string(wantJson), string(actualJson)) @@ -333,12 +333,12 @@ func Test_WrapWithEventsHandler(t *testing.T) { Method: "GET", Path: "/greeting", // Id: got.Data.(map[string]interface{})["id"].(string), - Id: got.Data.(map[string]interface{})["request_info"].(map[string]interface{})["id"].(string), + Id: got.Data.(map[string]any)["request_info"].(map[string]any)["id"].(string), } - hdr := map[string]interface{}{ - "id": got.Data.(map[string]interface{})["id"].(string), - "timestamp": got.Data.(map[string]interface{})["timestamp"].(string), - "response": got.Data.(map[string]interface{})["response"].(map[string]interface{}), + hdr := map[string]any{ + "id": got.Data.(map[string]any)["id"].(string), + "timestamp": got.Data.(map[string]any)["timestamp"].(string), + "response": got.Data.(map[string]any)["response"].(map[string]any), } wantJson := testJson(t, event.AuditType, &info, event.Op(tt.name), got, hdr, nil) assert.JSONEq(string(wantJson), string(actualJson)) @@ -466,7 +466,7 @@ type testMockBroker struct { errorOnFlush bool } -func (b *testMockBroker) Send(ctx context.Context, t eventlogger.EventType, payload interface{}) (eventlogger.Status, error) { +func (b *testMockBroker) Send(ctx context.Context, t eventlogger.EventType, payload any) (eventlogger.Status, error) { const op = "common.(testMockBroker).Send" _, isGateable := payload.(gated.Gateable) switch { @@ -488,12 +488,12 @@ func (b *testMockBroker) SetSuccessThreshold(t eventlogger.EventType, successThr } type eventJson struct { - CreatedAt string `json:"created_at"` - EventType string `json:"event_type"` - Payload map[string]interface{} `json:"payload"` + CreatedAt string `json:"created_at"` + EventType string `json:"event_type"` + Payload map[string]any `json:"payload"` } -func testJson(t *testing.T, eventType event.Type, reqInfo *event.RequestInfo, caller event.Op, got *cloudevents.Event, hdr, details map[string]interface{}) []byte { +func testJson(t *testing.T, eventType event.Type, reqInfo *event.RequestInfo, caller event.Op, got *cloudevents.Event, hdr, details map[string]any) []byte { t.Helper() const ( testAuditVersion = "v0.1" @@ -503,10 +503,10 @@ func testJson(t *testing.T, eventType event.Type, reqInfo *event.RequestInfo, ca require := require.New(t) - var payload map[string]interface{} + var payload map[string]any switch eventType { case event.ObservationType: - payload = map[string]interface{}{ + payload = map[string]any{ event.RequestInfoField: reqInfo, event.VersionField: testObservationVersion, } @@ -514,8 +514,8 @@ func testJson(t *testing.T, eventType event.Type, reqInfo *event.RequestInfo, ca payload[k] = v } case event.AuditType: - payload = map[string]interface{}{ - event.IdField: got.Data.(map[string]interface{})[event.IdField].(string), + payload = map[string]any{ + event.IdField: got.Data.(map[string]any)[event.IdField].(string), event.RequestInfoField: reqInfo, event.VersionField: testAuditVersion, event.TypeField: event.ApiRequest, @@ -536,11 +536,11 @@ func testJson(t *testing.T, eventType event.Type, reqInfo *event.RequestInfo, ca if details != nil { details[event.OpField] = string(caller) - d := got.Data.(map[string]interface{})[event.DetailsField].([]interface{})[0].(map[string]interface{}) - j.Data.(map[string]interface{})[event.DetailsField] = []struct { - CreatedAt string `json:"created_at"` - Type string `json:"type"` - Payload map[string]interface{} `json:"payload"` + d := got.Data.(map[string]any)[event.DetailsField].([]any)[0].(map[string]any) + j.Data.(map[string]any)[event.DetailsField] = []struct { + CreatedAt string `json:"created_at"` + Type string `json:"type"` + Payload map[string]any `json:"payload"` }{ { CreatedAt: d[event.CreatedAtField].(string), diff --git a/internal/daemon/controller/auth/auth.go b/internal/daemon/controller/auth/auth.go index 350bfc91b6..6331b1ba11 100644 --- a/internal/daemon/controller/auth/auth.go +++ b/internal/daemon/controller/auth/auth.go @@ -85,7 +85,7 @@ type VerifyResults struct { // RoundTripValue can be set to allow the function performing authentication // (often accompanied by lookup(s)) to return a result of that lookup to the // calling function. It is opaque to this package. - RoundTripValue interface{} + RoundTripValue any // Used for additional verification v *verifier diff --git a/internal/daemon/controller/auth/auth_test.go b/internal/daemon/controller/auth/auth_test.go index 97c8b995a3..58fe2fc079 100644 --- a/internal/daemon/controller/auth/auth_test.go +++ b/internal/daemon/controller/auth/auth_test.go @@ -240,7 +240,7 @@ func TestVerify_AuditEvent(t *testing.T) { got := api.CloudEventFromFile(t, eventConfig.AuditEvents.Name()) if tt.wantAuthAuditData { - auth, ok := got.Data.(map[string]interface{})["auth"].(map[string]interface{}) + auth, ok := got.Data.(map[string]any)["auth"].(map[string]any) require.True(ok) assert.Equal(encrypt.RedactedData, auth["email"]) assert.Equal(encrypt.RedactedData, auth["name"]) @@ -249,7 +249,7 @@ func TestVerify_AuditEvent(t *testing.T) { assert.Equal(true, auth["disabled_auth_entirely"]) } if tt.wantUserId != "" { - userInfo, ok := auth["user_info"].(map[string]interface{}) + userInfo, ok := auth["user_info"].(map[string]any) require.True(ok) assert.Equal(tt.wantUserId, userInfo["id"]) } diff --git a/internal/daemon/controller/cors_test.go b/internal/daemon/controller/cors_test.go index 9261d2a1b2..795ee5d21a 100644 --- a/internal/daemon/controller/cors_test.go +++ b/internal/daemon/controller/cors_test.go @@ -222,14 +222,14 @@ func TestHandler_CORS(t *testing.T) { var req *retryablehttp.Request // This tests out scope_id handling from body or query - var body interface{} + var body any scopeId := "global" if c.provideScopeId { scopeId = org.GetPublicId() } if c.method == http.MethodPost { - body = map[string]interface{}{ + body = map[string]any{ "scope_id": scopeId, } } diff --git a/internal/daemon/controller/handler.go b/internal/daemon/controller/handler.go index 26111017ac..cb0a4b87eb 100644 --- a/internal/daemon/controller/handler.go +++ b/internal/daemon/controller/handler.go @@ -461,8 +461,8 @@ func wrapHandlerWithCors(h http.Handler, props HandlerProperties) http.Handler { } type cmdAttrs struct { - Command string `json:"command,omitempty"` - Attributes interface{} `json:"attributes,omitempty"` + Command string `json:"command,omitempty"` + Attributes any `json:"attributes,omitempty"` } func wrapHandlerWithCallbackInterceptor(h http.Handler, c *Controller) http.Handler { @@ -526,7 +526,7 @@ func wrapHandlerWithCallbackInterceptor(h http.Handler, c *Controller) http.Hand switch { case useForm: if len(req.Form) > 0 { - values := make(map[string]interface{}, len(req.Form)) + values := make(map[string]any, len(req.Form)) // This won't handle repeated values. That's fine, at least for now. // We can address that if needed, which seems unlikely. for k := range req.Form { diff --git a/internal/daemon/controller/handler_test.go b/internal/daemon/controller/handler_test.go index 393004e507..4ca71eb295 100644 --- a/internal/daemon/controller/handler_test.go +++ b/internal/daemon/controller/handler_test.go @@ -26,8 +26,8 @@ func TestAuthenticationHandler(t *testing.T) { }) defer c.Shutdown() - request := map[string]interface{}{ - "attributes": map[string]interface{}{ + request := map[string]any{ + "attributes": map[string]any{ "login_name": "admin", "password": "password123", }, @@ -43,11 +43,11 @@ func TestAuthenticationHandler(t *testing.T) { b, err = ioutil.ReadAll(resp.Body) require.NoError(t, err) - body := make(map[string]interface{}) + body := make(map[string]any) require.NoError(t, json.Unmarshal(b, &body)) require.Contains(t, body, "attributes") - attrs := body["attributes"].(map[string]interface{}) + attrs := body["attributes"].(map[string]any) pubId, tok := attrs["id"].(string), attrs["token"].(string) assert.NotEmpty(t, pubId) assert.NotEmpty(t, tok) @@ -64,10 +64,10 @@ func TestAuthenticationHandler(t *testing.T) { b, err = ioutil.ReadAll(resp.Body) require.NoError(t, err) - body = make(map[string]interface{}) + body = make(map[string]any) require.NoError(t, json.Unmarshal(b, &body)) - attrs = body["attributes"].(map[string]interface{}) + attrs = body["attributes"].(map[string]any) require.Contains(t, attrs, "id") require.Contains(t, attrs, "auth_method_id") @@ -302,7 +302,7 @@ func TestCallbackInterceptor(t *testing.T) { }, wantJson: &cmdAttrs{ Command: "callback", - Attributes: map[string]interface{}{ + Attributes: map[string]any{ "state": "fooBar", "token": "barFoo", }, diff --git a/internal/daemon/controller/handlers/accounts/account_service.go b/internal/daemon/controller/handlers/accounts/account_service.go index 2dd60e6e23..12af47fb2a 100644 --- a/internal/daemon/controller/handlers/accounts/account_service.go +++ b/internal/daemon/controller/handlers/accounts/account_service.go @@ -886,7 +886,7 @@ func toProto(ctx context.Context, in auth.Account, opt ...handlers.Option) (*pb. }, } if s := i.GetTokenClaims(); s != "" { - m := make(map[string]interface{}) + m := make(map[string]any) var err error if err = json.Unmarshal([]byte(s), &m); err != nil { return nil, errors.Wrap(ctx, err, op, errors.WithMsg("error unmarshaling stored token claims")) @@ -896,7 +896,7 @@ func toProto(ctx context.Context, in auth.Account, opt ...handlers.Option) (*pb. } } if s := i.GetUserinfoClaims(); s != "" { - m := make(map[string]interface{}) + m := make(map[string]any) var err error if err = json.Unmarshal([]byte(s), &m); err != nil { return nil, errors.Wrap(ctx, err, op, errors.WithMsg("error unmarshaling stored userinfo claims")) diff --git a/internal/daemon/controller/handlers/authmethods/oidc_test.go b/internal/daemon/controller/handlers/authmethods/oidc_test.go index f9c7fa79fc..48535d5261 100644 --- a/internal/daemon/controller/handlers/authmethods/oidc_test.go +++ b/internal/daemon/controller/handlers/authmethods/oidc_test.go @@ -1535,7 +1535,7 @@ func TestAuthenticate_OIDC_Start(t *testing.T) { Attrs: &pbs.AuthenticateRequest_OidcStartAttributes{ OidcStartAttributes: &pbs.OidcStartAttributes{ RoundtripPayload: func() *structpb.Struct { - ret, err := structpb.NewStruct(map[string]interface{}{ + ret, err := structpb.NewStruct(map[string]any{ "foo": "bar", "baz": true, }) diff --git a/internal/daemon/controller/handlers/credentiallibraries/credentiallibrary_service.go b/internal/daemon/controller/handlers/credentiallibraries/credentiallibrary_service.go index 362782b223..c42ec1d70b 100644 --- a/internal/daemon/controller/handlers/credentiallibraries/credentiallibrary_service.go +++ b/internal/daemon/controller/handlers/credentiallibraries/credentiallibrary_service.go @@ -524,7 +524,7 @@ func toProto(in credential.Library, opt ...handlers.Option) (*pb.CredentialLibra if outputFields.Has(globals.CredentialTypeField) && vaultIn.GetCredentialType() != string(credential.UnspecifiedType) { out.CredentialType = vaultIn.GetCredentialType() if outputFields.Has(globals.CredentialMappingOverridesField) && vaultIn.MappingOverride != nil { - m := make(map[string]interface{}) + m := make(map[string]any) switch mapping := vaultIn.MappingOverride.(type) { case *vault.UsernamePasswordOverride: if mapping.UsernameAttribute != "" { @@ -716,7 +716,7 @@ func validateListRequest(req *pbs.ListCredentialLibrariesRequest) error { return nil } -func validateMapping(badFields map[string]string, credentialType credential.Type, overrides map[string]interface{}) { +func validateMapping(badFields map[string]string, credentialType credential.Type, overrides map[string]any) { validFields := make(map[string]bool) switch credentialType { case "", credential.UnspecifiedType: @@ -747,8 +747,8 @@ func validateMapping(badFields map[string]string, credentialType credential.Type } } -func getMappingUpdates(credentialType credential.Type, current vault.MappingOverride, new map[string]interface{}, apiMasks []string) (map[string]interface{}, bool) { - ret := make(map[string]interface{}) +func getMappingUpdates(credentialType credential.Type, current vault.MappingOverride, new map[string]any, apiMasks []string) (map[string]any, bool) { + ret := make(map[string]any) masks := make(map[string]bool) for _, m := range apiMasks { if m == credentialMappingPathField { @@ -769,7 +769,7 @@ func getMappingUpdates(credentialType credential.Type, current vault.MappingOver switch credentialType { case credential.UsernamePasswordType: - var currentUser, currentPass interface{} + var currentUser, currentPass any if overrides, ok := current.(*vault.UsernamePasswordOverride); ok { currentUser = overrides.UsernameAttribute currentPass = overrides.PasswordAttribute @@ -790,7 +790,7 @@ func getMappingUpdates(credentialType credential.Type, current vault.MappingOver } case credential.SshPrivateKeyType: - var currentUser, currentpPass, currentPk interface{} + var currentUser, currentpPass, currentPk any if overrides, ok := current.(*vault.SshPrivateKeyOverride); ok { currentUser = overrides.UsernameAttribute currentPk = overrides.PrivateKeyAttribute diff --git a/internal/daemon/controller/handlers/credentiallibraries/credentiallibrary_service_test.go b/internal/daemon/controller/handlers/credentiallibraries/credentiallibrary_service_test.go index 1cea6997ba..b4c635c09c 100644 --- a/internal/daemon/controller/handlers/credentiallibraries/credentiallibrary_service_test.go +++ b/internal/daemon/controller/handlers/credentiallibraries/credentiallibrary_service_test.go @@ -328,7 +328,7 @@ func TestCreate(t *testing.T) { }, CredentialType: string(credential.UsernamePasswordType), CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "user-test", "invalid": "invalid-test", } @@ -452,7 +452,7 @@ func TestCreate(t *testing.T) { }, }, CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "user-test", } ret, err := structpb.NewStruct(v) @@ -480,7 +480,7 @@ func TestCreate(t *testing.T) { }, CredentialType: string(credential.UsernamePasswordType), CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "user-test", } ret, err := structpb.NewStruct(v) @@ -501,7 +501,7 @@ func TestCreate(t *testing.T) { }, }, CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "user-test", passwordAttribute: "pass-test", } @@ -530,7 +530,7 @@ func TestCreate(t *testing.T) { }, CredentialType: string(credential.UsernamePasswordType), CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "user-test", passwordAttribute: "pass-test", } @@ -585,7 +585,7 @@ func TestCreate(t *testing.T) { }, }, CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "user-test", privateKeyAttribute: "pk-test", pkPassphraseAttribute: "pass-test", @@ -615,7 +615,7 @@ func TestCreate(t *testing.T) { }, CredentialType: string(credential.SshPrivateKeyType), CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "user-test", privateKeyAttribute: "pk-test", pkPassphraseAttribute: "pass-test", @@ -765,7 +765,7 @@ func TestGet(t *testing.T) { }, CredentialType: "username_password", CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "user", passwordAttribute: "pass", } @@ -797,7 +797,7 @@ func TestGet(t *testing.T) { }, CredentialType: "ssh_private_key", CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "user", privateKeyAttribute: "pk", pkPassphraseAttribute: "pass", @@ -1048,7 +1048,7 @@ func TestUpdate(t *testing.T) { UpdateMask: fieldmask(usernameAttrField), Item: &pb.CredentialLibrary{ CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "changed-user", } ret, err := structpb.NewStruct(v) @@ -1077,7 +1077,7 @@ func TestUpdate(t *testing.T) { UpdateMask: fieldmask(passwordAttrField), Item: &pb.CredentialLibrary{ CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ passwordAttribute: "changed-pass", } ret, err := structpb.NewStruct(v) @@ -1106,7 +1106,7 @@ func TestUpdate(t *testing.T) { UpdateMask: fieldmask(passwordAttrField, usernameAttrField), Item: &pb.CredentialLibrary{ CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "changed-user", passwordAttribute: "changed-pass", } @@ -1132,7 +1132,7 @@ func TestUpdate(t *testing.T) { UpdateMask: fieldmask(passwordAttrField, usernameAttrField), Item: &pb.CredentialLibrary{ CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "new-user", passwordAttribute: "new-pass", } @@ -1144,7 +1144,7 @@ func TestUpdate(t *testing.T) { }, res: func(in *pb.CredentialLibrary) *pb.CredentialLibrary { out := proto.Clone(in).(*pb.CredentialLibrary) - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "new-user", passwordAttribute: "new-pass", } @@ -1207,7 +1207,7 @@ func TestUpdate(t *testing.T) { UpdateMask: fieldmask(passwordAttrField, usernameAttrField), Item: &pb.CredentialLibrary{ CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: nil, passwordAttribute: nil, } @@ -1232,7 +1232,7 @@ func TestUpdate(t *testing.T) { UpdateMask: fieldmask(passwordAttrField, usernameAttrField), Item: &pb.CredentialLibrary{ CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: nil, passwordAttribute: nil, } @@ -1263,7 +1263,7 @@ func TestUpdate(t *testing.T) { UpdateMask: fieldmask(usernameAttrField), Item: &pb.CredentialLibrary{ CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "changed-user", } ret, err := structpb.NewStruct(v) @@ -1293,7 +1293,7 @@ func TestUpdate(t *testing.T) { UpdateMask: fieldmask(privateKeyAttrField), Item: &pb.CredentialLibrary{ CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ privateKeyAttribute: "changed-pk", } ret, err := structpb.NewStruct(v) @@ -1323,7 +1323,7 @@ func TestUpdate(t *testing.T) { UpdateMask: fieldmask(passphraseAttrField), Item: &pb.CredentialLibrary{ CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ pkPassphraseAttribute: "changed-pass", } ret, err := structpb.NewStruct(v) @@ -1353,7 +1353,7 @@ func TestUpdate(t *testing.T) { UpdateMask: fieldmask(privateKeyAttrField, usernameAttrField, passphraseAttrField), Item: &pb.CredentialLibrary{ CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "changed-user", privateKeyAttribute: "changed-pk", pkPassphraseAttribute: "changed-pass", @@ -1381,7 +1381,7 @@ func TestUpdate(t *testing.T) { UpdateMask: fieldmask(privateKeyAttrField, usernameAttrField, passphraseAttrField), Item: &pb.CredentialLibrary{ CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "new-user", privateKeyAttribute: "new-pk", pkPassphraseAttribute: "new-pass", @@ -1394,7 +1394,7 @@ func TestUpdate(t *testing.T) { }, res: func(in *pb.CredentialLibrary) *pb.CredentialLibrary { out := proto.Clone(in).(*pb.CredentialLibrary) - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: "new-user", privateKeyAttribute: "new-pk", pkPassphraseAttribute: "new-pass", @@ -1460,7 +1460,7 @@ func TestUpdate(t *testing.T) { UpdateMask: fieldmask(privateKeyAttrField, usernameAttrField, passphraseAttrField), Item: &pb.CredentialLibrary{ CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: nil, privateKeyAttribute: nil, pkPassphraseAttribute: nil, @@ -1486,7 +1486,7 @@ func TestUpdate(t *testing.T) { UpdateMask: fieldmask(privateKeyAttrField, usernameAttrField), Item: &pb.CredentialLibrary{ CredentialMappingOverrides: func() *structpb.Struct { - v := map[string]interface{}{ + v := map[string]any{ usernameAttribute: nil, privateKeyAttribute: nil, } diff --git a/internal/daemon/controller/handlers/credentials/credential_service.go b/internal/daemon/controller/handlers/credentials/credential_service.go index a9620ad3d8..558df4e8c6 100644 --- a/internal/daemon/controller/handlers/credentials/credential_service.go +++ b/internal/daemon/controller/handlers/credentials/credential_service.go @@ -697,7 +697,7 @@ func toJsonStorageCredential(ctx context.Context, storeId string, in *pb.Credent attrs := in.GetJsonAttributes() object := attrs.GetObject() if object == nil { - object, err = structpb.NewStruct(map[string]interface{}{}) + object, err = structpb.NewStruct(map[string]any{}) if err != nil { return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to build credential")) } diff --git a/internal/daemon/controller/handlers/errors.go b/internal/daemon/controller/handlers/errors.go index c23e59164a..352d3b554a 100644 --- a/internal/daemon/controller/handlers/errors.go +++ b/internal/daemon/controller/handlers/errors.go @@ -73,7 +73,7 @@ func ApiErrorWithCode(c codes.Code) error { } // ApiErrorWithCodeAndMessage returns an api error with the provided code and message. -func ApiErrorWithCodeAndMessage(c codes.Code, msg string, args ...interface{}) error { +func ApiErrorWithCodeAndMessage(c codes.Code, msg string, args ...any) error { return &ApiError{ Status: int32(runtime.HTTPStatusFromCode(c)), Inner: &pb.Error{ @@ -95,7 +95,7 @@ func NotFoundError() error { } // NotFoundErrorf returns an ApiError indicating a resource couldn't be found. -func NotFoundErrorf(msg string, a ...interface{}) *ApiError { +func NotFoundErrorf(msg string, a ...any) *ApiError { return &ApiError{ Status: http.StatusNotFound, Inner: &pb.Error{ diff --git a/internal/daemon/controller/handlers/filtering.go b/internal/daemon/controller/handlers/filtering.go index 7695af3bd4..df0d09e2fa 100644 --- a/internal/daemon/controller/handlers/filtering.go +++ b/internal/daemon/controller/handlers/filtering.go @@ -9,7 +9,7 @@ import ( // filterItem captures all the different namespaces that can be used when // filtering an item. type filterItem struct { - Item interface{} `json:"item"` + Item any `json:"item"` } type Filter struct { @@ -34,7 +34,7 @@ func NewFilter(f string) (*Filter, error) { // If the filter does not match the structure of the object being Matched, false is returned. // TODO: Support more than just matching against the item being filtered. Also allow matching against // values in the request or the request context itself. -func (f *Filter) Match(item interface{}) bool { +func (f *Filter) Match(item any) bool { if f.eval == nil { return true } diff --git a/internal/daemon/controller/handlers/filtering_test.go b/internal/daemon/controller/handlers/filtering_test.go index 2882487f2f..1b3e890431 100644 --- a/internal/daemon/controller/handlers/filtering_test.go +++ b/internal/daemon/controller/handlers/filtering_test.go @@ -11,7 +11,7 @@ import ( func TestNewFilter_everythingMatchesEmpty(t *testing.T) { f, err := NewFilter("") require.NoError(t, err) - for _, v := range []interface{}{ + for _, v := range []any{ nil, "foo", "", @@ -39,7 +39,7 @@ func TestNewFilter(t *testing.T) { name string filter string fErr bool - in interface{} + in any match bool }{ { diff --git a/internal/daemon/controller/handlers/host_catalogs/host_catalog_service_test.go b/internal/daemon/controller/handlers/host_catalogs/host_catalog_service_test.go index 14bfb8a4ae..355edf3caf 100644 --- a/internal/daemon/controller/handlers/host_catalogs/host_catalog_service_test.go +++ b/internal/daemon/controller/handlers/host_catalogs/host_catalog_service_test.go @@ -1390,7 +1390,7 @@ func TestUpdate_Plugin(t *testing.T) { ctx := auth.DisabledAuthTestContext(iamRepoFn, proj.GetPublicId()) freshCatalog := func(t *testing.T) *pb.HostCatalog { - attr, err := structpb.NewStruct(map[string]interface{}{ + attr, err := structpb.NewStruct(map[string]any{ "foo": "bar", }) require.NoError(t, err) @@ -1474,7 +1474,7 @@ func TestUpdate_Plugin(t *testing.T) { changes: []updateFn{ clearReadOnlyFields(), updateAttrs(func() *structpb.Struct { - attr, err := structpb.NewStruct(map[string]interface{}{ + attr, err := structpb.NewStruct(map[string]any{ "newkey": "newvalue", "foo": nil, }) @@ -1483,7 +1483,7 @@ func TestUpdate_Plugin(t *testing.T) { }()), }, check: func(t *testing.T, in *pb.HostCatalog) { - assert.Equal(t, map[string]interface{}{"newkey": "newvalue"}, in.GetAttributes().AsMap()) + assert.Equal(t, map[string]any{"newkey": "newvalue"}, in.GetAttributes().AsMap()) }, }, { @@ -1506,7 +1506,7 @@ func TestUpdate_Plugin(t *testing.T) { changes: []updateFn{ clearReadOnlyFields(), updateSecrets(func() *structpb.Struct { - attr, err := structpb.NewStruct(map[string]interface{}{ + attr, err := structpb.NewStruct(map[string]any{ "key1": "val1", }) require.NoError(t, err) diff --git a/internal/daemon/controller/handlers/host_sets/host_set_service_test.go b/internal/daemon/controller/handlers/host_sets/host_set_service_test.go index 04625fff1e..6c04e05502 100644 --- a/internal/daemon/controller/handlers/host_sets/host_set_service_test.go +++ b/internal/daemon/controller/handlers/host_sets/host_set_service_test.go @@ -842,7 +842,7 @@ func TestCreate_Plugin(t *testing.T) { } hc := plugin.TestCatalog(t, conn, proj.GetPublicId(), plg.GetPublicId()) - attrs := map[string]interface{}{ + attrs := map[string]any{ "int": 1, "zero int": 0, "string": "foo", @@ -851,7 +851,7 @@ func TestCreate_Plugin(t *testing.T) { "zero bytes": nil, "bool": true, "zero bool": false, - "nested": map[string]interface{}{ + "nested": map[string]any{ "int": 1, "zero int": 0, "string": "foo", @@ -866,7 +866,7 @@ func TestCreate_Plugin(t *testing.T) { require.NoError(t, err) // The result should clear out all keys with nil values... delete(attrs, "zero bytes") - delete(attrs["nested"].(map[string]interface{}), "zero bytes") + delete(attrs["nested"].(map[string]any), "zero bytes") testOutputAttrs, err := structpb.NewStruct(attrs) require.NoError(t, err) @@ -1491,7 +1491,7 @@ func TestUpdate_Plugin(t *testing.T) { ctx := auth.DisabledAuthTestContext(iamRepoFn, proj.GetPublicId()) freshSet := func(t *testing.T) *pb.HostSet { - attr, err := structpb.NewStruct(map[string]interface{}{ + attr, err := structpb.NewStruct(map[string]any{ "foo": "bar", }) require.NoError(t, err) @@ -1578,7 +1578,7 @@ func TestUpdate_Plugin(t *testing.T) { changes: []updateFn{ clearReadOnlyFields(), updateAttrs(func() *structpb.Struct { - attr, err := structpb.NewStruct(map[string]interface{}{ + attr, err := structpb.NewStruct(map[string]any{ "newkey": "newvalue", "foo": nil, }) @@ -1587,7 +1587,7 @@ func TestUpdate_Plugin(t *testing.T) { }()), }, check: func(t *testing.T, in *pb.HostSet) { - assert.Equal(t, map[string]interface{}{"newkey": "newvalue"}, in.GetAttributes().AsMap()) + assert.Equal(t, map[string]any{"newkey": "newvalue"}, in.GetAttributes().AsMap()) }, }, { diff --git a/internal/daemon/controller/handlers/targets/credentials.go b/internal/daemon/controller/handlers/targets/credentials.go index eb1034ec4f..f680971502 100644 --- a/internal/daemon/controller/handlers/targets/credentials.go +++ b/internal/daemon/controller/handlers/targets/credentials.go @@ -67,14 +67,14 @@ func dynamicToSessionCredential(ctx context.Context, cred credential.Dynamic) (* } var sSecret *structpb.Struct switch secret.(type) { - case map[string]interface{}: + case map[string]any: // In this case we actually have to re-decode it. The proto wrappers // choke on json.Number and at the time I'm writing this I don't // have time to write a walk function to dig through with reflect // and find all json.Numbers and replace them. So we eat the // inefficiency. So note that we are specifically _not_ using a // decoder with UseNumber here. - var dSecret map[string]interface{} + var dSecret map[string]any if err := json.Unmarshal(jSecret, &dSecret); err != nil { return nil, errors.Wrap(ctx, err, op, errors.WithMsg("decoding json for proto marshaling")) } @@ -178,7 +178,7 @@ func staticToSessionCredential(ctx context.Context, cred credential.Static) (*pb var credType string var credData *structpb.Struct - var secret map[string]interface{} + var secret map[string]any switch c := cred.(type) { case *credstatic.UsernamePasswordCredential: var err error @@ -189,7 +189,7 @@ func staticToSessionCredential(ctx context.Context, cred credential.Static) (*pb Password: string(c.GetPassword()), }, ) - secret = map[string]interface{}{ + secret = map[string]any{ "username": c.GetUsername(), "password": string(c.GetPassword()), } @@ -207,7 +207,7 @@ func staticToSessionCredential(ctx context.Context, cred credential.Static) (*pb PrivateKeyPassphrase: string(c.GetPrivateKeyPassphrase()), }, ) - secret = map[string]interface{}{ + secret = map[string]any{ "username": c.GetUsername(), "private_key": string(c.GetPrivateKey()), } @@ -221,7 +221,7 @@ func staticToSessionCredential(ctx context.Context, cred credential.Static) (*pb case *credstatic.JsonCredential: var err error credType = string(credential.JsonType) - object := map[string]interface{}{} + object := map[string]any{} err = json.Unmarshal(c.GetObject(), &object) if err != nil { return nil, errors.New(ctx, errors.InvalidParameter, op, "unmarshalling json") diff --git a/internal/daemon/controller/handlers/targets/registry.go b/internal/daemon/controller/handlers/targets/registry.go index e2494983fb..38abaa41a8 100644 --- a/internal/daemon/controller/handlers/targets/registry.go +++ b/internal/daemon/controller/handlers/targets/registry.go @@ -28,7 +28,7 @@ type Attributes interface { VetForUpdate([]string) map[string]string } -type attributeFunc func(interface{}) Attributes +type attributeFunc func(any) Attributes type setAttributeFunc func(target.Target, *pb.Target) error @@ -67,7 +67,7 @@ func (r registry) maskManager(s subtypes.Subtype) (handlers.MaskManager, error) // newAttribute creates an Attribute for the given subtype. It delegates the // allocation of the Attribute to the registered attrFunc for the given // subtype. An error is returned if the provided subtype is not registered -func (r registry) newAttribute(s subtypes.Subtype, m interface{}) (Attributes, error) { +func (r registry) newAttribute(s subtypes.Subtype, m any) (Attributes, error) { re, err := r.get(s) if err != nil { return nil, err diff --git a/internal/daemon/controller/handlers/targets/target_service.go b/internal/daemon/controller/handlers/targets/target_service.go index 09733c7c24..dca4bb063f 100644 --- a/internal/daemon/controller/handlers/targets/target_service.go +++ b/internal/daemon/controller/handlers/targets/target_service.go @@ -1823,7 +1823,7 @@ func (w workerList) workerInfos() []*pb.WorkerInfo { func (w workerList) filtered(eval *bexpr.Evaluator) (workerList, error) { var ret []*server.Worker for _, worker := range w { - filterInput := map[string]interface{}{ + filterInput := map[string]any{ "name": worker.GetName(), "tags": worker.CanonicalTags(), } diff --git a/internal/daemon/controller/handlers/targets/tcp/target_service_test.go b/internal/daemon/controller/handlers/targets/tcp/target_service_test.go index fcaceacd9f..0918e3835f 100644 --- a/internal/daemon/controller/handlers/targets/tcp/target_service_test.go +++ b/internal/daemon/controller/handlers/targets/tcp/target_service_test.go @@ -2453,7 +2453,7 @@ func TestAuthorizeSession(t *testing.T) { }}, // TODO: validate the contents of the authorization token is what is expected } - wantSecret := map[string]interface{}{ + wantSecret := map[string]any{ "certificate": "-----BEGIN CERTIFICATE-----\n", "issuing_ca": "-----BEGIN CERTIFICATE-----\n", "private_key": "-----BEGIN RSA PRIVATE KEY-----\n", @@ -2780,7 +2780,7 @@ func TestAuthorizeSessionTypedCredentials(t *testing.T) { CredentialType: string(credential.UsernamePasswordType), }, Credential: func() *structpb.Struct { - data := map[string]interface{}{ + data := map[string]any{ "password": "my-pass", "username": "my-user", } @@ -2806,7 +2806,7 @@ func TestAuthorizeSessionTypedCredentials(t *testing.T) { CredentialType: string(credential.UsernamePasswordType), }, Credential: func() *structpb.Struct { - data := map[string]interface{}{ + data := map[string]any{ "password": "my-pass", "username": "my-user", } @@ -2832,7 +2832,7 @@ func TestAuthorizeSessionTypedCredentials(t *testing.T) { CredentialType: string(credential.UsernamePasswordType), }, Credential: func() *structpb.Struct { - data := map[string]interface{}{ + data := map[string]any{ "password": "static-password", "username": "static-username", } @@ -2858,7 +2858,7 @@ func TestAuthorizeSessionTypedCredentials(t *testing.T) { CredentialType: string(credential.SshPrivateKeyType), }, Credential: func() *structpb.Struct { - data := map[string]interface{}{ + data := map[string]any{ "private_key": string(testdata.PEMBytes["ed25519"]), "username": "static-username", } @@ -2884,7 +2884,7 @@ func TestAuthorizeSessionTypedCredentials(t *testing.T) { CredentialType: string(credential.SshPrivateKeyType), }, Credential: func() *structpb.Struct { - data := map[string]interface{}{ + data := map[string]any{ "private_key": "my-pk", "username": "my-user", } @@ -2910,7 +2910,7 @@ func TestAuthorizeSessionTypedCredentials(t *testing.T) { CredentialType: string(credential.SshPrivateKeyType), }, Credential: func() *structpb.Struct { - data := map[string]interface{}{ + data := map[string]any{ "username": "my-user", "private_key": "my-special-pk", } @@ -2936,7 +2936,7 @@ func TestAuthorizeSessionTypedCredentials(t *testing.T) { CredentialType: string(credential.SshPrivateKeyType), }, Credential: func() *structpb.Struct { - data := map[string]interface{}{ + data := map[string]any{ "private_key_passphrase": testdata.PEMEncryptedKeys[0].EncryptionKey, "private_key": string(testdata.PEMEncryptedKeys[0].PEMBytes), "username": "static-username", @@ -2963,7 +2963,7 @@ func TestAuthorizeSessionTypedCredentials(t *testing.T) { CredentialType: string(credential.SshPrivateKeyType), }, Credential: func() *structpb.Struct { - data := map[string]interface{}{ + data := map[string]any{ "username": "my-user", "private_key": "my-pk", "private_key_passphrase": "my-pass", @@ -2990,7 +2990,7 @@ func TestAuthorizeSessionTypedCredentials(t *testing.T) { CredentialType: string(credential.SshPrivateKeyType), }, Credential: func() *structpb.Struct { - data := map[string]interface{}{ + data := map[string]any{ "username": "my-user", "private_key": "my-special-pk", "private_key_passphrase": "my-special-pass", @@ -3132,7 +3132,7 @@ func TestAuthorizeSession_Errors(t *testing.T) { // Set previous token to expired in the database and revoke in Vault to validate a // credential store with an expired token is correctly returned over the API num, err := rw.Exec(context.Background(), "update credential_vault_token set status = ? where store_id = ?", - []interface{}{vault.ExpiredToken, expiredStore.PublicId}) + []any{vault.ExpiredToken, expiredStore.PublicId}) require.NoError(t, err) assert.Equal(t, 1, num) v.RevokeToken(t, tok1) @@ -3319,9 +3319,9 @@ func TestAuthorizeSession_Errors(t *testing.T) { } } -func decodeJsonSecret(t *testing.T, in string) map[string]interface{} { +func decodeJsonSecret(t *testing.T, in string) map[string]any { t.Helper() - ret := make(map[string]interface{}) + ret := make(map[string]any) dec := json.NewDecoder(base64.NewDecoder(base64.StdEncoding, strings.NewReader(in))) require.NoError(t, dec.Decode(&ret)) return ret diff --git a/internal/daemon/controller/handlers/targets/tcp/tcp.go b/internal/daemon/controller/handlers/targets/tcp/tcp.go index 5f937e9d05..f379fda13b 100644 --- a/internal/daemon/controller/handlers/targets/tcp/tcp.go +++ b/internal/daemon/controller/handlers/targets/tcp/tcp.go @@ -47,7 +47,7 @@ func (a *attribute) VetForUpdate(p []string) map[string]string { return badFields } -func newAttribute(m interface{}) targets.Attributes { +func newAttribute(m any) targets.Attributes { a := &attribute{ &pb.TcpTargetAttributes{}, } diff --git a/internal/daemon/controller/handlers/workers/worker_service.go b/internal/daemon/controller/handlers/workers/worker_service.go index ea2d4c9568..dd6d4f94c8 100644 --- a/internal/daemon/controller/handlers/workers/worker_service.go +++ b/internal/daemon/controller/handlers/workers/worker_service.go @@ -841,9 +841,9 @@ func toProto(ctx context.Context, in *server.Worker, opt ...handlers.Option) (*p } func tagsToMapProto(in map[string][]string) (map[string]*structpb.ListValue, error) { - b := make(map[string][]interface{}) + b := make(map[string][]any) for k, v := range in { - result := make([]interface{}, 0, len(v)) + result := make([]any, 0, len(v)) for _, t := range v { result = append(result, t) } diff --git a/internal/daemon/controller/handlers/workers/worker_service_test.go b/internal/daemon/controller/handlers/workers/worker_service_test.go index d4c6acff1f..b02926e753 100644 --- a/internal/daemon/controller/handlers/workers/worker_service_test.go +++ b/internal/daemon/controller/handlers/workers/worker_service_test.go @@ -43,7 +43,7 @@ var testAuthorizedActions = []string{"no-op", "read", "update", "delete", "add-w func structListValue(t *testing.T, ss ...string) *structpb.ListValue { t.Helper() - var val []interface{} + var val []any for _, s := range ss { val = append(val, s) } diff --git a/internal/daemon/controller/interceptor.go b/internal/daemon/controller/interceptor.go index f4d15b4860..840246512e 100644 --- a/internal/daemon/controller/interceptor.go +++ b/internal/daemon/controller/interceptor.go @@ -73,10 +73,10 @@ func requestCtxInterceptor( } // Authorization unary interceptor function to handle authorize per RPC call return func(interceptorCtx context.Context, - req interface{}, + req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler, - ) (interface{}, error) { + ) (any, error) { md, ok := metadata.FromIncomingContext(interceptorCtx) if !ok { return nil, errors.New(interceptorCtx, errors.Internal, op, "No metadata") @@ -149,9 +149,9 @@ func errorInterceptor( ) grpc.UnaryServerInterceptor { const op = "controller.errorInterceptor" return func(interceptorCtx context.Context, - req interface{}, + req any, _ *grpc.UnaryServerInfo, - handler grpc.UnaryHandler) (interface{}, error, + handler grpc.UnaryHandler) (any, error, ) { // call the handler... h, handlerErr := handler(interceptorCtx, req) @@ -200,9 +200,9 @@ func statusCodeInterceptor( ) grpc.UnaryServerInterceptor { const op = "controller.statusCodeInterceptor" return func(interceptorCtx context.Context, - req interface{}, + req any, _ *grpc.UnaryServerInfo, - handler grpc.UnaryHandler) (interface{}, error, + handler grpc.UnaryHandler) (any, error, ) { // call the handler... h, handlerErr := handler(interceptorCtx, req) @@ -220,7 +220,7 @@ func statusCodeInterceptor( } } -func isNil(i interface{}) bool { +func isNil(i any) bool { if i == nil { return true } @@ -236,9 +236,9 @@ func auditRequestInterceptor( ) grpc.UnaryServerInterceptor { const op = "controller.auditRequestInterceptor" return func(interceptorCtx context.Context, - req interface{}, + req any, _ *grpc.UnaryServerInfo, - handler grpc.UnaryHandler) (interface{}, error, + handler grpc.UnaryHandler) (any, error, ) { if msg, ok := req.(proto.Message); ok { // Clone the request before writing it to the audit log, @@ -258,9 +258,9 @@ func auditResponseInterceptor( ) grpc.UnaryServerInterceptor { const op = "controller.auditResponseInterceptor" return func(interceptorCtx context.Context, - req interface{}, + req any, _ *grpc.UnaryServerInfo, - handler grpc.UnaryHandler) (interface{}, error, + handler grpc.UnaryHandler) (any, error, ) { // call the handler... resp, err := handler(interceptorCtx, req) @@ -284,10 +284,10 @@ func workerRequestInfoInterceptor(ctx context.Context, eventer *event.Eventer) ( return nil, errors.New(ctx, errors.InvalidParameter, op, "missing eventer") } return func(interceptorCtx context.Context, - req interface{}, + req any, srvInfo *grpc.UnaryServerInfo, handler grpc.UnaryHandler, - ) (interface{}, error) { + ) (any, error) { var err error id, err := event.NewId(event.IdPrefix) if err != nil { @@ -316,7 +316,7 @@ func workerRequestInfoInterceptor(ctx context.Context, eventer *event.Eventer) ( func recoveryHandler() grpc_recovery.RecoveryHandlerFuncContext { const op = "controller.recoveryHandler" - return func(ctx context.Context, p interface{}) (err error) { + return func(ctx context.Context, p any) (err error) { event.WriteError( ctx, op, diff --git a/internal/daemon/controller/interceptor_test.go b/internal/daemon/controller/interceptor_test.go index e6a5039a77..f0f64b5b6a 100644 --- a/internal/daemon/controller/interceptor_test.go +++ b/internal/daemon/controller/interceptor_test.go @@ -83,7 +83,7 @@ func Test_requestCtxInterceptor(t *testing.T) { factoryCtx := context.Background() - returnCtxHandler := func(ctx context.Context, req interface{}) (interface{}, error) { + returnCtxHandler := func(ctx context.Context, req any) (any, error) { return ctx, nil } @@ -468,7 +468,7 @@ func Test_workerRequestInfoInterceptor(t *testing.T) { factoryCtx := context.Background() requestCtx := context.Background() - returnCtxHandler := func(ctx context.Context, req interface{}) (interface{}, error) { + returnCtxHandler := func(ctx context.Context, req any) (any, error) { return ctx, nil } diff --git a/internal/daemon/controller/multi_test.go b/internal/daemon/controller/multi_test.go index 2b4886d1b8..e15e78c715 100644 --- a/internal/daemon/controller/multi_test.go +++ b/internal/daemon/controller/multi_test.go @@ -31,14 +31,14 @@ func TestAuthenticationMulti(t *testing.T) { defer c2.Shutdown() auth := authmethods.NewClient(c1.Client()) - token1Result, err := auth.Authenticate(c1.Context(), c1.Server().DevPasswordAuthMethodId, "login", map[string]interface{}{"login_name": c1.Server().DevLoginName, "password": c1.Server().DevPassword}) + token1Result, err := auth.Authenticate(c1.Context(), c1.Server().DevPasswordAuthMethodId, "login", map[string]any{"login_name": c1.Server().DevLoginName, "password": c1.Server().DevPassword}) require.Nil(err) token1 := new(authtokens.AuthToken) require.NoError(json.Unmarshal(token1Result.GetRawAttributes(), token1)) require.NotNil(token1) auth = authmethods.NewClient(c2.Client()) - token2Result, err := auth.Authenticate(c2.Context(), c2.Server().DevPasswordAuthMethodId, "login", map[string]interface{}{"login_name": c2.Server().DevLoginName, "password": c2.Server().DevPassword}) + token2Result, err := auth.Authenticate(c2.Context(), c2.Server().DevPasswordAuthMethodId, "login", map[string]any{"login_name": c2.Server().DevLoginName, "password": c2.Server().DevPassword}) require.Nil(err) token2 := new(authtokens.AuthToken) require.NoError(json.Unmarshal(token2Result.GetRawAttributes(), token2)) diff --git a/internal/daemon/controller/testing.go b/internal/daemon/controller/testing.go index ae50315758..f370d44a2b 100644 --- a/internal/daemon/controller/testing.go +++ b/internal/daemon/controller/testing.go @@ -164,7 +164,7 @@ func (tc *TestController) Token() *authtokens.AuthToken { tc.Context(), tc.b.DevPasswordAuthMethodId, "login", - map[string]interface{}{ + map[string]any{ "login_name": tc.b.DevLoginName, "password": tc.b.DevPassword, }, @@ -190,7 +190,7 @@ func (tc *TestController) UnprivilegedToken() *authtokens.AuthToken { tc.Context(), tc.b.DevPasswordAuthMethodId, "login", - map[string]interface{}{ + map[string]any{ "login_name": tc.b.DevUnprivilegedLoginName, "password": tc.b.DevUnprivilegedPassword, }, @@ -794,7 +794,7 @@ func (tc *TestController) WaitForNextWorkerStatusUpdate(workerStatusName string) } var waitStatusCurrent time.Time - tc.Controller().WorkerStatusUpdateTimes().Range(func(k, v interface{}) bool { + tc.Controller().WorkerStatusUpdateTimes().Range(func(k, v any) bool { if k == nil || v == nil { err = fmt.Errorf("nil key or value on entry: key=%#v value=%#v", k, v) return false diff --git a/internal/daemon/metric/testing.go b/internal/daemon/metric/testing.go index d6df76cdfb..5e40311f08 100644 --- a/internal/daemon/metric/testing.go +++ b/internal/daemon/metric/testing.go @@ -37,7 +37,7 @@ type TestInvoker struct { RetErr error } -func (i *TestInvoker) Invoke(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, opts ...grpc.CallOption) error { +func (i *TestInvoker) Invoke(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, opts ...grpc.CallOption) error { i.Called = true require.NotNil(i.T, ctx) diff --git a/internal/daemon/worker/internal/metric/cluster_client.go b/internal/daemon/worker/internal/metric/cluster_client.go index 3413e6f181..b2acd15074 100644 --- a/internal/daemon/worker/internal/metric/cluster_client.go +++ b/internal/daemon/worker/internal/metric/cluster_client.go @@ -40,7 +40,7 @@ var expectedGrpcClientCodes = []codes.Code{ // observations for the collectors associated with gRPC connections // between the cluster and its clients. func InstrumentClusterClient() 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 { r := metric.NewGrpcRequestRecorder(method, grpcRequestLatency) err := invoker(ctx, method, req, reply, cc, opts...) r.Record(err) diff --git a/internal/daemon/worker/session/manager.go b/internal/daemon/worker/session/manager.go index 9c86d34d2e..1322b23cab 100644 --- a/internal/daemon/worker/session/manager.go +++ b/internal/daemon/worker/session/manager.go @@ -127,7 +127,7 @@ func (m *manager) RequestCloseConnections(ctx context.Context, closeInfo map[str return closeConnections(ctx, m.controllerSessionConn, m, closeInfo) } -func isNil(i interface{}) bool { +func isNil(i any) bool { if i == nil { return true } diff --git a/internal/db/assert/asserts.go b/internal/db/assert/asserts.go index 57586f5224..736c1ea992 100644 --- a/internal/db/assert/asserts.go +++ b/internal/db/assert/asserts.go @@ -27,21 +27,21 @@ func (a *DbAsserts) Log(enable bool) { } // IsNull asserts that the resource fieldName is null in the db. -func (a *DbAsserts) IsNull(resource interface{}, fieldName string) bool { +func (a *DbAsserts) IsNull(resource any, fieldName string) bool { return a.asserts.IsNull(resource, fieldName) } // NotNull asserts that the resource fieldName is not null in the db. -func (a *DbAsserts) NotNull(resource interface{}, fieldName string) bool { +func (a *DbAsserts) NotNull(resource any, fieldName string) bool { return a.asserts.NotNull(resource, fieldName) } // Nullable asserts that the resource fieldName is nullable in the db. -func (a *DbAsserts) Nullable(resource interface{}, fieldName string) bool { +func (a *DbAsserts) Nullable(resource any, fieldName string) bool { return a.asserts.Nullable(resource, fieldName) } // Domain asserts that the resource fieldName is the domainName in the db. -func (a *DbAsserts) Domain(resource interface{}, fieldName, domainName string) bool { +func (a *DbAsserts) Domain(resource any, fieldName, domainName string) bool { return a.asserts.Domain(resource, fieldName, domainName) } diff --git a/internal/db/changesafe_reader_writer.go b/internal/db/changesafe_reader_writer.go index 36fd0ead6a..c365450dc6 100644 --- a/internal/db/changesafe_reader_writer.go +++ b/internal/db/changesafe_reader_writer.go @@ -100,6 +100,6 @@ func (w *changeSafeDbwWriter) ScanRows(rows *sql.Rows, result any) error { return dbw.New(w.db.underlying.wrapped.Load()).ScanRows(rows, result) } -func (w *changeSafeDbwWriter) Update(ctx context.Context, i interface{}, fieldMaskPaths []string, setToNullPaths []string, opt ...dbw.Option) (int, error) { +func (w *changeSafeDbwWriter) Update(ctx context.Context, i any, fieldMaskPaths []string, setToNullPaths []string, opt ...dbw.Option) (int, error) { return dbw.New(w.db.underlying.wrapped.Load()).Update(ctx, i, fieldMaskPaths, setToNullPaths, opt...) } diff --git a/internal/db/clause.go b/internal/db/clause.go index 854f59621a..e6b5b3bbd9 100644 --- a/internal/db/clause.go +++ b/internal/db/clause.go @@ -7,7 +7,7 @@ import ( // ColumnValue defines a column and it's assigned value for a database operation type ColumnValue struct { column string - value interface{} + value any } // column represents a table column @@ -20,7 +20,7 @@ type column struct { // Expr(...) to create these values. type ExprValue struct { sql string - vars []interface{} + vars []any } // Expr creates an expression value (ExprValue) which can be used when setting @@ -33,12 +33,12 @@ type ExprValue struct { // Set exp_time column to N seconds from now: // // SetColumnValues(map[string]interface{}{"exp_time": Expr("wt_add_seconds_to_now(?)", 10)}) -func Expr(expr string, args ...interface{}) ExprValue { +func Expr(expr string, args ...any) ExprValue { return ExprValue{sql: expr, vars: args} } // SetColumnValues defines a map from column names to values -func SetColumnValues(columnValues map[string]interface{}) []ColumnValue { +func SetColumnValues(columnValues map[string]any) []ColumnValue { keys := make([]string, 0, len(columnValues)) for key := range columnValues { keys = append(keys, key) @@ -72,14 +72,14 @@ type OnConflict struct { // be any one of these: // Columns: the name of a specific column or columns // Constraint: the name of a unique constraint - Target interface{} + Target any // Action specifies the action to take on conflict. This can be any one of // these: // DoNothing: leaves the conflicting record as-is // UpdateAll: updates all the columns of the conflicting record using the resource's data // []ColumnValue: update a set of columns of the conflicting record using the set of assignments - Action interface{} + Action any } // Constraint defines database constraint name diff --git a/internal/db/db_test/db.go b/internal/db/db_test/db.go index 12218629ac..056b716b95 100644 --- a/internal/db/db_test/db.go +++ b/internal/db/db_test/db.go @@ -41,7 +41,7 @@ func AllocTestUser() TestUser { } // Clone is useful when you're retrying transactions and you need to send the user several times -func (u *TestUser) Clone() interface{} { +func (u *TestUser) Clone() any { s := proto.Clone(u.StoreTestUser) return &TestUser{ StoreTestUser: s.(*StoreTestUser), @@ -139,7 +139,7 @@ func NewTestScooter() (*TestScooter, error) { }, nil } -func (t *TestScooter) Clone() interface{} { +func (t *TestScooter) Clone() any { s := proto.Clone(t.StoreTestScooter) return &TestScooter{ StoreTestScooter: s.(*StoreTestScooter), @@ -169,7 +169,7 @@ func NewTestAccessory(description string) (*TestAccessory, error) { return &TestAccessory{StoreTestAccessory: &StoreTestAccessory{Description: description}}, nil } -func (t *TestAccessory) Clone() interface{} { +func (t *TestAccessory) Clone() any { s := proto.Clone(t.StoreTestAccessory) return &TestAccessory{ StoreTestAccessory: s.(*StoreTestAccessory), @@ -204,7 +204,7 @@ func NewTestScooterAccessory(scooterId, accessoryId uint32) (*TestScooterAccesso }, nil } -func (t *TestScooterAccessory) Clone() interface{} { +func (t *TestScooterAccessory) Clone() any { s := proto.Clone(t.StoreTestScooterAccessory) return &TestScooterAccessory{ StoreTestScooterAccessory: s.(*StoreTestScooterAccessory), @@ -223,11 +223,11 @@ func (t *TestScooterAccessory) SetTableName(name string) { } type Cloner interface { - Clone() interface{} + Clone() any } type NotIder struct{} -func (i *NotIder) Clone() interface{} { +func (i *NotIder) Clone() any { return &NotIder{} } diff --git a/internal/db/option.go b/internal/db/option.go index 399aec53a1..d801e57fa6 100644 --- a/internal/db/option.go +++ b/internal/db/option.go @@ -21,7 +21,7 @@ func GetOpts(opt ...Option) Options { return opts } -func getDbwOptions(ctx context.Context, rw *Db, i interface{}, opType OpType, opt ...Option) ([]dbw.Option, error) { +func getDbwOptions(ctx context.Context, rw *Db, i any, opType OpType, opt ...Option) ([]dbw.Option, error) { const op = "db.getDbwOptions" opts := GetOpts(opt...) dbwOpts := make([]dbw.Option, 0, len(opt)) @@ -32,7 +32,7 @@ func getDbwOptions(ctx context.Context, rw *Db, i interface{}, opType OpType, op before := oplogBefore if !opts.withSkipVetForWrite && (opType != DeleteOp && opType != DeleteItemsOp) { if vetter, ok := i.(VetForWriter); ok { - before = func(i interface{}) error { + before = func(i any) error { if err := vetter.VetForWrite(ctx, rw, opType, opt...); err != nil { return err } @@ -161,7 +161,7 @@ type Options struct { withSkipVetForWrite bool withWhereClause string - withWhereClauseArgs []interface{} + withWhereClauseArgs []any withOrder string // withPrngValues is used to switch the ID generation to a pseudo-random mode @@ -281,7 +281,7 @@ func WithSkipVetForWrite(enable bool) Option { // WithWhere provides an option to provide a where clause with arguments for an // operation. -func WithWhere(whereClause string, args ...interface{}) Option { +func WithWhere(whereClause string, args ...any) Option { return func(o *Options) { o.withWhereClause = whereClause o.withWhereClauseArgs = append(o.withWhereClauseArgs, args...) diff --git a/internal/db/option_test.go b/internal/db/option_test.go index 6f2546108b..cbaebdf91d 100644 --- a/internal/db/option_test.go +++ b/internal/db/option_test.go @@ -157,7 +157,7 @@ func Test_getOpts(t *testing.T) { assert.Equal(opts, testOpts) opts = GetOpts(WithWhere("id = ? and foo = ?", 1234, "bar")) testOpts.withWhereClause = "id = ? and foo = ?" - testOpts.withWhereClauseArgs = []interface{}{1234, "bar"} + testOpts.withWhereClauseArgs = []any{1234, "bar"} assert.Equal(opts, testOpts) }) t.Run("WithOrder", func(t *testing.T) { @@ -231,7 +231,7 @@ func Test_getOpts(t *testing.T) { testOpts := getDefaultOptions() assert.Equal(opts, testOpts) columns := SetColumns([]string{"name", "description"}) - columnValues := SetColumnValues(map[string]interface{}{"expiration": "NULL"}) + columnValues := SetColumnValues(map[string]any{"expiration": "NULL"}) testOnConflict := OnConflict{ Target: Constraint("uniq-name"), Action: append(columns, columnValues...), diff --git a/internal/db/read_writer.go b/internal/db/read_writer.go index 3035f988cf..508a8c714d 100644 --- a/internal/db/read_writer.go +++ b/internal/db/read_writer.go @@ -44,28 +44,28 @@ type Reader interface { // ResourcePrivateIder interface, then they are used as the resource's // primary key for lookup. Otherwise, the resource tags are used to // determine it's primary key(s) for lookup. - LookupById(ctx context.Context, resource interface{}, opt ...Option) error + LookupById(ctx context.Context, resource any, opt ...Option) error // LookupByPublicId will lookup resource by its public_id which must be unique. LookupByPublicId(ctx context.Context, resource ResourcePublicIder, opt ...Option) error // LookupWhere will lookup and return the first resource using a where clause with parameters - LookupWhere(ctx context.Context, resource interface{}, where string, args []interface{}, opt ...Option) error + LookupWhere(ctx context.Context, resource any, where string, args []any, opt ...Option) error // SearchWhere will search for all the resources it can find using a where // clause with parameters. Supports the WithLimit option. If // WithLimit < 0, then unlimited results are returned. If WithLimit == 0, then // default limits are used for results. - SearchWhere(ctx context.Context, resources interface{}, where string, args []interface{}, opt ...Option) error + SearchWhere(ctx context.Context, resources any, where string, args []any, opt ...Option) error // Query will run the raw query and return the *sql.Rows results. Query will // operate within the context of any ongoing transaction for the db.Reader. The // caller must close the returned *sql.Rows. Query can/should be used in // combination with ScanRows. - Query(ctx context.Context, sql string, values []interface{}, opt ...Option) (*sql.Rows, error) + Query(ctx context.Context, sql string, values []any, opt ...Option) (*sql.Rows, error) // ScanRows will scan sql rows into the interface provided - ScanRows(ctx context.Context, rows *sql.Rows, result interface{}) error + ScanRows(ctx context.Context, rows *sql.Rows, result any) error } // Writer interface defines create, update and retryable transaction handlers @@ -83,14 +83,14 @@ type Writer interface { // error is returned the caller must decide what to do with the transaction, // which almost always should be to rollback. Update returns the number of // rows updated or an error. Supported options: WithOplog. - Update(ctx context.Context, i interface{}, fieldMaskPaths []string, setToNullPaths []string, opt ...Option) (int, error) + Update(ctx context.Context, i any, fieldMaskPaths []string, setToNullPaths []string, opt ...Option) (int, error) // Create an object in the db with options: WithDebug, WithOplog, NewOplogMsg, // WithLookup, WithReturnRowsAffected, OnConflict, WithVersion, and // WithWhere. The caller is responsible for the transaction life cycle of // the writer and if an error is returned the caller must decide what to do // with the transaction, which almost always should be to rollback. - Create(ctx context.Context, i interface{}, opt ...Option) error + Create(ctx context.Context, i any, opt ...Option) error // CreateItems will create multiple items of the same type. // Supported options: WithDebug, WithOplog, WithOplogMsgs, @@ -100,14 +100,14 @@ type Writer interface { // cycle of the writer and if an error is returned the caller must decide // what to do with the transaction, which almost always should be to // rollback. - CreateItems(ctx context.Context, createItems []interface{}, opt ...Option) error + CreateItems(ctx context.Context, createItems []any, opt ...Option) error // Delete an object in the db with options: WithOplog, WithDebug. // The caller is responsible for the transaction life cycle of the writer // and if an error is returned the caller must decide what to do with // the transaction, which almost always should be to rollback. Delete // returns the number of rows deleted or an error. - Delete(ctx context.Context, i interface{}, opt ...Option) (int, error) + Delete(ctx context.Context, i any, opt ...Option) (int, error) // DeleteItems will delete multiple items of the same type. // Supported options: WithOplog and WithOplogMsgs. WithOplog and @@ -115,23 +115,23 @@ type Writer interface { // transaction life cycle of the writer and if an error is returned the // caller must decide what to do with the transaction, which almost always // should be to rollback. Delete returns the number of rows deleted or an error. - DeleteItems(ctx context.Context, deleteItems []interface{}, opt ...Option) (int, error) + DeleteItems(ctx context.Context, deleteItems []any, opt ...Option) (int, error) // Exec will execute the sql with the values as parameters. The int returned // is the number of rows affected by the sql. No options are currently // supported. - Exec(ctx context.Context, sql string, values []interface{}, opt ...Option) (int, error) + Exec(ctx context.Context, sql string, values []any, opt ...Option) (int, error) // Query will run the raw query and return the *sql.Rows results. Query will // operate within the context of any ongoing transaction for the db.Writer. The // caller must close the returned *sql.Rows. Query can/should be used in // combination with ScanRows. Query is included in the Writer interface // so callers can execute updates and inserts with returning values. - Query(ctx context.Context, sql string, values []interface{}, opt ...Option) (*sql.Rows, error) + Query(ctx context.Context, sql string, values []any, opt ...Option) (*sql.Rows, error) // GetTicket returns an oplog ticket for the aggregate root of "i" which can // be used to WriteOplogEntryWith for that aggregate root. - GetTicket(ctx context.Context, i interface{}) (*store.Ticket, error) + GetTicket(ctx context.Context, i any) (*store.Ticket, error) // WriteOplogEntryWith will write an oplog entry with the msgs provided for // the ticket's aggregateName. No options are currently supported. @@ -145,7 +145,7 @@ type Writer interface { ) error // ScanRows will scan sql rows into the interface provided - ScanRows(ctx context.Context, rows *sql.Rows, result interface{}) error + ScanRows(ctx context.Context, rows *sql.Rows, result any) error } const ( @@ -220,7 +220,7 @@ func (rw *Db) UnderlyingDB() func() *dbw.DB { // Exec will execute the sql with the values as parameters. The int returned // is the number of rows affected by the sql. WithDebug is supported. -func (rw *Db) Exec(ctx context.Context, sql string, values []interface{}, opt ...Option) (int, error) { +func (rw *Db) Exec(ctx context.Context, sql string, values []any, opt ...Option) (int, error) { const op = "db.Exec" if sql == "" { return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing sql") @@ -237,7 +237,7 @@ func (rw *Db) Exec(ctx context.Context, sql string, values []interface{}, opt .. // operate within the context of any ongoing transaction for the db.Reader. The // caller must close the returned *sql.Rows. Query can/should be used in // combination with ScanRows. -func (rw *Db) Query(ctx context.Context, sql string, values []interface{}, opt ...Option) (*sql.Rows, error) { +func (rw *Db) Query(ctx context.Context, sql string, values []any, opt ...Option) (*sql.Rows, error) { const op = "db.Query" if sql == "" { return nil, errors.New(ctx, errors.InvalidParameter, op, "missing sql") @@ -251,7 +251,7 @@ func (rw *Db) Query(ctx context.Context, sql string, values []interface{}, opt . } // Scan rows will scan the rows into the interface -func (rw *Db) ScanRows(ctx context.Context, rows *sql.Rows, result interface{}) error { +func (rw *Db) ScanRows(ctx context.Context, rows *sql.Rows, result any) error { const op = "db.ScanRows" if rw.underlying == nil { return errors.New(ctx, errors.InvalidParameter, op, "missing underlying db") @@ -280,7 +280,7 @@ func (rw *Db) ScanRows(ctx context.Context, rows *sql.Rows, result interface{}) // valid value for the WithVersion option and will return an error. WithWhere // allows specifying an additional constraint on the on conflict operation in // addition to the on conflict target policy (columns or constraint). -func (rw *Db) Create(ctx context.Context, i interface{}, opt ...Option) error { +func (rw *Db) Create(ctx context.Context, i any, opt ...Option) error { const op = "db.Create" if rw.underlying == nil { return errors.New(ctx, errors.InvalidParameter, op, "missing underlying db") @@ -299,7 +299,7 @@ func (rw *Db) Create(ctx context.Context, i interface{}, opt ...Option) error { // WithDebug, WithOplog, WithOplogMsgs, WithReturnRowsAffected, OnConflict, // WithVersion, and WithWhere WithOplog and WithOplogMsgs may not be used // together. WithLookup is not a supported option. -func (rw *Db) CreateItems(ctx context.Context, createItems []interface{}, opt ...Option) error { +func (rw *Db) CreateItems(ctx context.Context, createItems []any, opt ...Option) error { const op = "db.CreateItems" if rw.underlying == nil { return errors.New(ctx, errors.InvalidParameter, op, "missing underlying db") @@ -334,7 +334,7 @@ func (rw *Db) CreateItems(ctx context.Context, createItems []interface{}, opt .. // WithVersion option and will return an error. WithWhere allows specifying an // additional constraint on the operation in addition to the PKs. WithDebug will // turn on debugging for the update call. -func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string, setToNullPaths []string, opt ...Option) (int, error) { +func (rw *Db) Update(ctx context.Context, i any, fieldMaskPaths []string, setToNullPaths []string, opt ...Option) (int, error) { const op = "db.Update" if rw.underlying == nil { return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing underlying db") @@ -358,7 +358,7 @@ func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string // in-memory oplog message. WithOplog and NewOplogMsg cannot be used together. // WithWhere allows specifying an additional constraint on the operation in // addition to the PKs. Delete returns the number of rows deleted and any errors. -func (rw *Db) Delete(ctx context.Context, i interface{}, opt ...Option) (int, error) { +func (rw *Db) Delete(ctx context.Context, i any, opt ...Option) (int, error) { const op = "db.Delete" if rw.underlying == nil { return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing underlying db") @@ -377,7 +377,7 @@ func (rw *Db) Delete(ctx context.Context, i interface{}, opt ...Option) (int, er // DeleteItems will delete multiple items of the same type. Supported options: // WithOplog and WithOplogMsgs. WithOplog and WithOplogMsgs may not be used // together. -func (rw *Db) DeleteItems(ctx context.Context, deleteItems []interface{}, opt ...Option) (int, error) { +func (rw *Db) DeleteItems(ctx context.Context, deleteItems []any, opt ...Option) (int, error) { const op = "db.DeleteItems" if rw.underlying == nil { return NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing underlying db") @@ -450,7 +450,7 @@ func (w *Db) DoTx(ctx context.Context, retries uint, backOff Backoff, handler Tx // LookupByPublicId will lookup resource by its public_id or private_id, which // must be unique. WithDebug is the only valid option, all other options are ignored. -func (rw *Db) LookupById(ctx context.Context, resourceWithIder interface{}, opt ...Option) error { +func (rw *Db) LookupById(ctx context.Context, resourceWithIder any, opt ...Option) error { const op = "db.LookupById" if rw.underlying == nil { return errors.New(ctx, errors.InvalidParameter, op, "missing underlying db") @@ -476,7 +476,7 @@ func (rw *Db) LookupByPublicId(ctx context.Context, resource ResourcePublicIder, // LookupWhere will lookup the first resource using a where clause with // parameters (it only returns the first one). WithDebug is supported. -func (rw *Db) LookupWhere(ctx context.Context, resource interface{}, where string, args []interface{}, opt ...Option) error { +func (rw *Db) LookupWhere(ctx context.Context, resource any, where string, args []any, opt ...Option) error { const op = "db.LookupWhere" if rw.underlying == nil { return errors.New(ctx, errors.InvalidParameter, op, "missing underlying db") @@ -501,7 +501,7 @@ func (rw *Db) LookupWhere(ctx context.Context, resource interface{}, where strin // Supports the WithLimit option. If WithLimit < 0, then unlimited results are returned. // If WithLimit == 0, then default limits are used for results. // Supports the WithOrder and WithDebug options. -func (rw *Db) SearchWhere(ctx context.Context, resources interface{}, where string, args []interface{}, opt ...Option) error { +func (rw *Db) SearchWhere(ctx context.Context, resources any, where string, args []any, opt ...Option) error { const op = "db.SearchWhere" if rw.underlying == nil { return errors.New(ctx, errors.InvalidParameter, op, "missing underlying db") @@ -516,7 +516,7 @@ func (rw *Db) SearchWhere(ctx context.Context, resources interface{}, where stri return nil } -func isNil(i interface{}) bool { +func isNil(i any) bool { if i == nil { return true } diff --git a/internal/db/read_writer_ext_test.go b/internal/db/read_writer_ext_test.go index 628c765835..26a212d01c 100644 --- a/internal/db/read_writer_ext_test.go +++ b/internal/db/read_writer_ext_test.go @@ -57,7 +57,7 @@ func TestDb_Create_OnConflict(t *testing.T) { name: "set-column-values", onConflict: db.OnConflict{ Target: db.Columns{"public_id"}, - Action: db.SetColumnValues(map[string]interface{}{ + Action: db.SetColumnValues(map[string]any{ "name": db.Expr("md5(?)", "alice eve smith"), "email": "alice@gmail.com", "phone_number": db.Expr("NULL"), @@ -75,7 +75,7 @@ func TestDb_Create_OnConflict(t *testing.T) { } cv := db.SetColumns([]string{"name"}) cv = append(cv, - db.SetColumnValues(map[string]interface{}{ + db.SetColumnValues(map[string]any{ "email": "alice@gmail.com", "phone_number": db.Expr("NULL"), })...) @@ -216,7 +216,7 @@ func TestDb_Create_OnConflict(t *testing.T) { Target: db.Constraint("db_test_user_public_id_key"), Action: db.SetColumns([]string{"name"}), } - users := []interface{}{} + users := []any{} users = append(users, conflictUser) var rowsAffected int64 err = rw.CreateItems(ctx, users, db.WithOnConflict(&onConflict), db.WithOplog(wrapper, md), db.WithReturnRowsAffected(&rowsAffected)) diff --git a/internal/db/read_writer_oplog.go b/internal/db/read_writer_oplog.go index 75d95a32f4..994422308e 100644 --- a/internal/db/read_writer_oplog.go +++ b/internal/db/read_writer_oplog.go @@ -14,11 +14,11 @@ import ( ) type ( - beforeWriteFn func(interface{}) error - afterWriteFn func(interface{}, int) error + beforeWriteFn func(any) error + afterWriteFn func(any, int) error ) -func (rw *Db) generateOplogBeforeAfterOpts(ctx context.Context, i interface{}, opType OpType, opts Options) (beforeWriteFn, afterWriteFn, error) { +func (rw *Db) generateOplogBeforeAfterOpts(ctx context.Context, i any, opType OpType, opts Options) (beforeWriteFn, afterWriteFn, error) { const op = "db.generateOplogBeforeAfterOpts" withOplog := opts.withOplog if !withOplog && opts.newOplogMsg == nil && opts.newOplogMsgs == nil { @@ -35,7 +35,7 @@ func (rw *Db) generateOplogBeforeAfterOpts(ctx context.Context, i interface{}, o } var isSlice bool - var items []interface{} + var items []any rv := reflect.ValueOf(i) if isSlice = rv.Kind() == reflect.Slice; isSlice { for i := 0; i < rv.Len(); i++ { @@ -74,7 +74,7 @@ func (rw *Db) generateOplogBeforeAfterOpts(ctx context.Context, i interface{}, o var ticket *store.Ticket if opts.withOplog { - beforeFn = func(interface{}) error { + beforeFn = func(any) error { const op = "db.beforeFn" var err error switch isSlice { @@ -91,7 +91,7 @@ func (rw *Db) generateOplogBeforeAfterOpts(ctx context.Context, i interface{}, o } switch { case withOplog && (opType == CreateOp || opType == UpdateOp || opType == DeleteOp): - afterFn = func(i interface{}, rowsAffected int) error { + afterFn = func(i any, rowsAffected int) error { const op = "db.afterFnSingleItem" switch { case onConflictDoNothing && rowsAffected == 0: @@ -103,9 +103,9 @@ func (rw *Db) generateOplogBeforeAfterOpts(ctx context.Context, i interface{}, o return nil } case withOplog && (opType == CreateItemsOp || opType == DeleteItemsOp): - afterFn = func(i interface{}, rowsAffected int) error { + afterFn = func(i any, rowsAffected int) error { const op = "db.afterFnMultiItem" - err := rw.addOplogForItems(ctx, opType, opts, ticket, i.([]interface{})) + err := rw.addOplogForItems(ctx, opType, opts, ticket, i.([]any)) if err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg("returning oplog msgs failed")) } @@ -115,7 +115,7 @@ func (rw *Db) generateOplogBeforeAfterOpts(ctx context.Context, i interface{}, o if isSlice { return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "new oplog msg (singular) is not a supported option") } - afterFn = func(i interface{}, rowsAffected int) error { + afterFn = func(i any, rowsAffected int) error { const op = "db.afterFnNewOplogMsg" switch { case onConflictDoNothing && rowsAffected == 0: @@ -130,7 +130,7 @@ func (rw *Db) generateOplogBeforeAfterOpts(ctx context.Context, i interface{}, o } case opts.newOplogMsgs != nil: - afterFn = func(i interface{}, rowsAffected int) error { + afterFn = func(i any, rowsAffected int) error { const op = "db.afterFnNewOplogMsgs" if rowsAffected > 0 { msgs, err := rw.oplogMsgsForItems(ctx, CreateOp, opts, items) @@ -145,7 +145,7 @@ func (rw *Db) generateOplogBeforeAfterOpts(ctx context.Context, i interface{}, o return beforeFn, afterFn, nil } -func validateOplogArgs(ctx context.Context, i interface{}, opts Options) (oplog.ReplayableMessage, error) { +func validateOplogArgs(ctx context.Context, i any, opts Options) (oplog.ReplayableMessage, error) { const op = "db.validateOplogArgs" oplogArgs := opts.oplogOpts if oplogArgs.wrapper == nil { @@ -179,7 +179,7 @@ func (rw *Db) getTicketFor(ctx context.Context, aggregateName string) (*store.Ti // GetTicket returns an oplog ticket for the aggregate root of "i" which can // be used to WriteOplogEntryWith for that aggregate root. -func (rw *Db) GetTicket(ctx context.Context, i interface{}) (*store.Ticket, error) { +func (rw *Db) GetTicket(ctx context.Context, i any) (*store.Ticket, error) { const op = "db.GetTicket" if rw.underlying == nil { return nil, errors.New(ctx, errors.InvalidParameter, op, "missing underlying db", errors.WithoutEvent()) @@ -194,7 +194,7 @@ func (rw *Db) GetTicket(ctx context.Context, i interface{}) (*store.Ticket, erro return rw.getTicketFor(ctx, replayable.TableName()) } -func (rw *Db) oplogMsgsForItems(ctx context.Context, opType OpType, opts Options, items []interface{}) ([]*oplog.Message, error) { +func (rw *Db) oplogMsgsForItems(ctx context.Context, opType OpType, opts Options, items []any) ([]*oplog.Message, error) { const op = "db.oplogMsgsForItems" if len(items) == 0 { return nil, errors.New(ctx, errors.InvalidParameter, op, "missing items", errors.WithoutEvent()) @@ -221,7 +221,7 @@ func (rw *Db) oplogMsgsForItems(ctx context.Context, opType OpType, opts Options // addOplogForItems will add a multi-message oplog entry with one msg for each // item. Items must all be of the same type. Only CreateOp and DeleteOp are // currently supported operations. -func (rw *Db) addOplogForItems(ctx context.Context, opType OpType, opts Options, ticket *store.Ticket, items []interface{}) error { +func (rw *Db) addOplogForItems(ctx context.Context, opType OpType, opts Options, ticket *store.Ticket, items []any) error { const op = "db.addOplogForItems" oplogArgs := opts.oplogOpts if ticket == nil { @@ -271,7 +271,7 @@ func (rw *Db) addOplogForItems(ctx context.Context, opType OpType, opts Options, return nil } -func (rw *Db) addOplog(ctx context.Context, opType OpType, opts Options, ticket *store.Ticket, i interface{}) error { +func (rw *Db) addOplog(ctx context.Context, opType OpType, opts Options, ticket *store.Ticket, i any) error { const op = "db.addOplog" oplogArgs := opts.oplogOpts replayable, err := validateOplogArgs(ctx, i, opts) @@ -357,7 +357,7 @@ func (rw *Db) WriteOplogEntryWith(ctx context.Context, wrapper wrapping.Wrapper, return nil } -func (rw *Db) newOplogMessage(ctx context.Context, opType OpType, i interface{}, opt ...Option) (*oplog.Message, error) { +func (rw *Db) newOplogMessage(ctx context.Context, opType OpType, i any, opt ...Option) (*oplog.Message, error) { const op = "db.newOplogMessage" opts := GetOpts(opt...) replayable, ok := i.(oplog.ReplayableMessage) diff --git a/internal/db/read_writer_test.go b/internal/db/read_writer_test.go index aedc1f7083..89beff0e8e 100644 --- a/internal/db/read_writer_test.go +++ b/internal/db/read_writer_test.go @@ -362,7 +362,7 @@ func TestDb_Update(t *testing.T) { } where = fmt.Sprintf("%s and %s is null", where, f) } - err = rw.LookupWhere(context.Background(), foundUser, where, []interface{}{tt.args.i.PublicId}) + err = rw.LookupWhere(context.Background(), foundUser, where, []any{tt.args.i.PublicId}) require.NoError(err) assert.Equal(tt.args.i.Id, foundUser.Id) assert.Equal(tt.wantName, foundUser.Name) @@ -878,7 +878,7 @@ func TestDb_LookupWhere(t *testing.T) { assert.NotEmpty(user.PublicId) var foundUser db_test.TestUser - err = w.LookupWhere(context.Background(), &foundUser, "public_id = ?", []interface{}{user.PublicId}) + err = w.LookupWhere(context.Background(), &foundUser, "public_id = ?", []any{user.PublicId}) require.NoError(err) assert.Equal(foundUser.Id, user.Id) }) @@ -886,7 +886,7 @@ func TestDb_LookupWhere(t *testing.T) { assert, require := assert.New(t), require.New(t) w := Db{} var foundUser db_test.TestUser - err := w.LookupWhere(context.Background(), &foundUser, "public_id = ?", []interface{}{1}) + err := w.LookupWhere(context.Background(), &foundUser, "public_id = ?", []any{1}) require.Error(err) assert.Equal("db.LookupWhere: missing underlying db: parameter violation: error #100", err.Error()) }) @@ -897,7 +897,7 @@ func TestDb_LookupWhere(t *testing.T) { require.NoError(err) var foundUser db_test.TestUser - err = w.LookupWhere(context.Background(), &foundUser, "public_id = ?", []interface{}{id}) + err = w.LookupWhere(context.Background(), &foundUser, "public_id = ?", []any{id}) require.Error(err) assert.True(errors.Match(errors.T(errors.RecordNotFound), err)) }) @@ -908,7 +908,7 @@ func TestDb_LookupWhere(t *testing.T) { require.NoError(err) var foundUser db_test.TestUser - err = w.LookupWhere(context.Background(), &foundUser, "? = ?", []interface{}{id}) + err = w.LookupWhere(context.Background(), &foundUser, "? = ?", []any{id}) require.Error(err) }) } @@ -941,7 +941,7 @@ func TestDb_LookupNotFoundEvent(t *testing.T) { require.NoError(err) var foundUser db_test.TestUser - err = w.LookupWhere(ctx, &foundUser, "public_id = ?", []interface{}{id}) + err = w.LookupWhere(ctx, &foundUser, "public_id = ?", []any{id}) require.Error(err) assert.True(errors.Match(errors.T(errors.RecordNotFound), err)) @@ -984,7 +984,7 @@ func TestDb_SearchWhere(t *testing.T) { type args struct { where string - arg []interface{} + arg []any opt []Option } tests := []struct { @@ -1035,7 +1035,7 @@ func TestDb_SearchWhere(t *testing.T) { createCnt: 1, args: args{ where: "public_id = ?", - arg: []interface{}{knownUser.PublicId}, + arg: []any{knownUser.PublicId}, opt: []Option{WithLimit(3)}, }, wantCnt: 1, @@ -1057,7 +1057,7 @@ func TestDb_SearchWhere(t *testing.T) { db: New(conn), createCnt: 1, args: args{ - arg: []interface{}{knownUser.PublicId}, + arg: []any{knownUser.PublicId}, opt: []Option{WithLimit(3)}, }, wantErr: true, @@ -1068,7 +1068,7 @@ func TestDb_SearchWhere(t *testing.T) { createCnt: 1, args: args{ where: "public_id = ?", - arg: []interface{}{"bad-id"}, + arg: []any{"bad-id"}, opt: []Option{WithLimit(3)}, }, wantCnt: 0, @@ -1080,7 +1080,7 @@ func TestDb_SearchWhere(t *testing.T) { createCnt: 1, args: args{ where: "bad_column_name = ?", - arg: []interface{}{knownUser.PublicId}, + arg: []any{knownUser.PublicId}, opt: []Option{WithLimit(3)}, }, wantCnt: 0, @@ -1092,7 +1092,7 @@ func TestDb_SearchWhere(t *testing.T) { createCnt: 1, args: args{ where: "public_id = ?", - arg: []interface{}{knownUser.PublicId}, + arg: []any{knownUser.PublicId}, opt: []Option{WithLimit(3)}, }, wantCnt: 0, @@ -1142,7 +1142,7 @@ func TestDb_Exec(t *testing.T) { err = w.Create(context.Background(), user) require.NoError(err) require.NotEmpty(user.Id) - rowsAffected, err := w.Exec(context.Background(), "update db_test_user set name = ? where public_id = ?", []interface{}{"updated-" + id, user.PublicId}) + rowsAffected, err := w.Exec(context.Background(), "update db_test_user set name = ? where public_id = ?", []any{"updated-" + id, user.PublicId}) require.NoError(err) require.Equal(1, rowsAffected) }) @@ -1594,7 +1594,7 @@ func TestDb_ScanRows(t *testing.T) { require.NoError(err) assert.NotEmpty(user.Id) where := "select * from db_test_user where name in (?, ?)" - rows, err := w.Query(context.Background(), where, []interface{}{"alice", "bob"}) + rows, err := w.Query(context.Background(), where, []any{"alice", "bob"}) require.NoError(err) defer func() { err := rows.Close(); assert.NoError(err) }() for rows.Next() { @@ -1625,7 +1625,7 @@ func TestDb_Query(t *testing.T) { assert.Equal("alice", user.Name) where := "select * from db_test_user where name in (?, ?)" - rows, err := rw.Query(context.Background(), where, []interface{}{"alice", "bob"}) + rows, err := rw.Query(context.Background(), where, []any{"alice", "bob"}) require.NoError(err) defer func() { err := rows.Close(); assert.NoError(err) }() for rows.Next() { @@ -1644,8 +1644,8 @@ func TestDb_CreateItems(t *testing.T) { TestCreateTables(t, db) testOplogResourceId := testId(t) - createFn := func() []interface{} { - results := []interface{}{} + createFn := func() []any { + results := []any{} for i := 0; i < 10; i++ { u, err := db_test.NewTestUser() require.NoError(t, err) @@ -1653,12 +1653,12 @@ func TestDb_CreateItems(t *testing.T) { } return results } - createMixedFn := func() []interface{} { + createMixedFn := func() []any { u, err := db_test.NewTestUser() require.NoError(t, err) c, err := db_test.NewTestCar() require.NoError(t, err) - return []interface{}{ + return []any{ u, c, } @@ -1667,7 +1667,7 @@ func TestDb_CreateItems(t *testing.T) { returnedMsgs := []*oplog.Message{} type args struct { - createItems []interface{} + createItems []any opt []Option } tests := []struct { @@ -1801,7 +1801,7 @@ func TestDb_CreateItems(t *testing.T) { name: "empty items", underlying: db, args: args{ - createItems: []interface{}{}, + createItems: []any{}, }, wantErr: true, wantErrIs: errors.InvalidParameter, @@ -1855,8 +1855,8 @@ func TestDb_DeleteItems(t *testing.T) { TestCreateTables(t, db) testOplogResourceId := testId(t) - createFn := func() []interface{} { - results := []interface{}{} + createFn := func() []any { + results := []any{} for i := 0; i < 10; i++ { u := testUser(t, db, "", "", "") results = append(results, u) @@ -1867,7 +1867,7 @@ func TestDb_DeleteItems(t *testing.T) { returnedMsgs := []*oplog.Message{} type args struct { - deleteItems []interface{} + deleteItems []any opt []Option } tests := []struct { @@ -1995,7 +1995,7 @@ func TestDb_DeleteItems(t *testing.T) { name: "empty items", underlying: db, args: args{ - deleteItems: []interface{}{}, + deleteItems: []any{}, }, wantErr: true, wantErrIs: errors.InvalidParameter, @@ -2152,7 +2152,7 @@ func TestDb_LookupById(t *testing.T) { scooterAccessory := testScooterAccessory(t, conn, scooter.Id, accessory.AccessoryId) type args struct { - resource interface{} + resource any opt []Option } tests := []struct { @@ -2203,7 +2203,7 @@ func TestDb_LookupById(t *testing.T) { name: "compond-with-zero-value-pk", underlying: conn, args: args{ - resource: func() interface{} { + resource: func() any { cp := scooterAccessory.Clone() cp.(*db_test.TestScooterAccessory).ScooterId = 0 return cp @@ -2287,7 +2287,7 @@ func TestDb_GetTicket(t *testing.T) { tests := []struct { name string underlying *DB - aggregateType interface{} + aggregateType any wantErr bool wantErrIs errors.Code }{ @@ -2971,7 +2971,7 @@ func TestDb_oplogMsgsForItems(t *testing.T) { // underlying isn't used at this point, so it can just be nil rw := Db{underlying: nil} - var users []interface{} + var users []any var wantUsrMsgs []*oplog.Message for i := 0; i < 5; i++ { publicId, err := base62.Random(20) @@ -2990,7 +2990,7 @@ func TestDb_oplogMsgsForItems(t *testing.T) { publicId, err := base62.Random(20) require.NoError(t, err) - mixed := []interface{}{ + mixed := []any{ &db_test.TestUser{StoreTestUser: &db_test.StoreTestUser{PublicId: publicId}}, &db_test.TestCar{StoreTestCar: &db_test.StoreTestCar{PublicId: publicId}}, } @@ -2998,7 +2998,7 @@ func TestDb_oplogMsgsForItems(t *testing.T) { type args struct { opType OpType opts Options - items []interface{} + items []any } tests := []struct { name string @@ -3029,7 +3029,7 @@ func TestDb_oplogMsgsForItems(t *testing.T) { name: "zero items", args: args{ opType: CreateOp, - items: []interface{}{}, + items: []any{}, }, wantErr: true, wantIsErr: errors.InvalidParameter, diff --git a/internal/db/schema/migrations/oss/postgres/9/managed_group_test.go b/internal/db/schema/migrations/oss/postgres/9/managed_group_test.go index 5fa2bf7958..48c48590dd 100644 --- a/internal/db/schema/migrations/oss/postgres/9/managed_group_test.go +++ b/internal/db/schema/migrations/oss/postgres/9/managed_group_test.go @@ -48,7 +48,7 @@ func Test_ManagedGroupTable(t *testing.T) { require := require.New(t) _, err := rw.Exec(context.Background(), "insert into auth_managed_group values (@public_id, @auth_method_id)", - []interface{}{ + []any{ sql.Named("public_id", tt.publicId), sql.Named("auth_method_id", tt.authMethodId), }) @@ -82,7 +82,7 @@ func Test_ManagedGroupTable(t *testing.T) { t.Run("update: "+tt.testName, func(t *testing.T) { assert := assert.New(t) _, err := rw.Exec(context.Background(), fmt.Sprintf("update auth_managed_group set %s = @value where public_id = @public_id", tt.column), - []interface{}{ + []any{ sql.Named("value", tt.value), sql.Named("public_id", tt.publicId), }) @@ -160,7 +160,7 @@ func Test_OidcManagedGroupTable(t *testing.T) { t.Run("insert: "+tt.testName, func(t *testing.T) { require := require.New(t) _, err := rw.Exec(ctx, "insert into auth_oidc_managed_group (public_id, auth_method_id, name, filter) values (@public_id, @auth_method_id, @name, @filter)", - []interface{}{ + []any{ sql.Named("public_id", tt.publicId), sql.Named("auth_method_id", tt.authMethodId), sql.Named("name", tt.name), @@ -187,7 +187,7 @@ func Test_OidcManagedGroupTable(t *testing.T) { updateTests := []struct { testName string column string - value interface{} + value any wantErr bool }{ { @@ -219,7 +219,7 @@ func Test_OidcManagedGroupTable(t *testing.T) { t.Run("update: "+tt.testName, func(t *testing.T) { require := require.New(t) _, err = rw.Exec(ctx, fmt.Sprintf("update auth_oidc_managed_group set %s = @value where public_id = @public_id", tt.column), - []interface{}{ + []any{ sql.Named("value", tt.value), sql.Named("public_id", managedGroupId), }) require.True(tt.wantErr == (err != nil)) @@ -247,7 +247,7 @@ func Test_OidcManagedGroupTable(t *testing.T) { assert.Equal(t, defaultOidcAuthMethodId, auth_method_id) // Delete the value from the subtype table - affected, err := rw.Exec(ctx, "delete from auth_oidc_managed_group where public_id = @public_id", []interface{}{sql.Named("public_id", managedGroupId)}) + affected, err := rw.Exec(ctx, "delete from auth_oidc_managed_group where public_id = @public_id", []any{sql.Named("public_id", managedGroupId)}) require.EqualValues(t, 1, affected) // It should no longer be in the base table @@ -271,7 +271,7 @@ func Test_AuthManagedOidcGroupMemberAccountTable(t *testing.T) { // Insert valid data in auth_oidc_managed_group to use for the following tests _, err := rw.Exec(ctx, "insert into auth_oidc_managed_group (public_id, auth_method_id, name, filter) values (@public_id, @auth_method_id, @name, @filter)", - []interface{}{ + []any{ sql.Named("public_id", managedGroupId), sql.Named("auth_method_id", defaultOidcAuthMethodId), sql.Named("name", name), @@ -324,7 +324,7 @@ func Test_AuthManagedOidcGroupMemberAccountTable(t *testing.T) { t.Run("insert: "+tt.testName, func(t *testing.T) { assert := assert.New(t) _, err = rw.Exec(ctx, "insert into auth_oidc_managed_group_member_account (managed_group_id, member_id) values (@group_id, @member_id)", - []interface{}{ + []any{ sql.Named("group_id", tt.managedGroupId), sql.Named("member_id", tt.memberId), }) @@ -347,7 +347,7 @@ func Test_AuthManagedOidcGroupMemberAccountTable(t *testing.T) { updateTests := []struct { testName string column string - value interface{} + value any wantErr bool }{ { @@ -373,7 +373,7 @@ func Test_AuthManagedOidcGroupMemberAccountTable(t *testing.T) { t.Run("update: "+tt.testName, func(t *testing.T) { assert := assert.New(t) _, err = rw.Exec(ctx, fmt.Sprintf("update auth_managed_group_member_account set %s = ? where managed_group_id = @group_id and member_id = @member_id", tt.column), - []interface{}{ + []any{ sql.Named("group_id", managedGroupId), sql.Named("member_id", accountId), }) diff --git a/internal/db/schema/migrations/oss/postgres_11_01_test.go b/internal/db/schema/migrations/oss/postgres_11_01_test.go index 28b129d620..d177173bcc 100644 --- a/internal/db/schema/migrations/oss/postgres_11_01_test.go +++ b/internal/db/schema/migrations/oss/postgres_11_01_test.go @@ -132,7 +132,7 @@ func Test_ServerEnumChanges(t *testing.T) { require.Nil(result) // Try adding a broken server type - result, err = d.ExecContext(ctx, insertServerQuery, []interface{}{"test-bad", "bad", "127.0.0.1"}...) + result, err = d.ExecContext(ctx, insertServerQuery, []any{"test-bad", "bad", "127.0.0.1"}...) require.EqualError(err, expectServerConstraintErr) require.Nil(result) diff --git a/internal/db/schema/migrations/oss/postgres_20_05_test.go b/internal/db/schema/migrations/oss/postgres_20_05_test.go index 67f282e34e..0d19877057 100644 --- a/internal/db/schema/migrations/oss/postgres_20_05_test.go +++ b/internal/db/schema/migrations/oss/postgres_20_05_test.go @@ -60,7 +60,7 @@ insert into iam_scope (parent_id, type, public_id, name) values ('global', 'org', ?, 'my-org-scope') -`, []interface{}{orgId}) +`, []any{orgId}) require.NoError(t, err) assert.Equal(t, 1, num) @@ -70,7 +70,7 @@ values insert into iam_scope (parent_id, type, public_id, name) values - (?, 'project', ?, 'my-project-scope')`, []interface{}{orgId, projectId}) + (?, 'project', ?, 'my-project-scope')`, []any{orgId, projectId}) require.NoError(t, err) assert.Equal(t, 1, num) @@ -80,7 +80,7 @@ values insert into static_host_catalog (scope_id, public_id, name) values - (?, ?, 'my-host-catalog')`, []interface{}{projectId, hostCatalogId}) + (?, ?, 'my-host-catalog')`, []any{projectId, hostCatalogId}) require.NoError(t, err) assert.Equal(t, 1, num) @@ -90,7 +90,7 @@ values insert into static_host_set (catalog_id, public_id, name) values - (?, ?, 'my-host-set')`, []interface{}{hostCatalogId, hostSetId}) + (?, ?, 'my-host-set')`, []any{hostCatalogId, hostSetId}) require.NoError(t, err) assert.Equal(t, 1, num) @@ -215,11 +215,11 @@ values for _, tt := range insertTests { t.Run("insert: "+tt.testName, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - _, err := rw.Exec(ctx, "delete from host_set_preferred_endpoint where host_set_id = ?", []interface{}{tt.hostSetId}) + _, err := rw.Exec(ctx, "delete from host_set_preferred_endpoint where host_set_id = ?", []any{tt.hostSetId}) require.NoError(err) // Add items to insert - var items []interface{} + var items []any for _, cond := range tt.conditions { ep := host.AllocPreferredEndpoint() ep.HostSetId = tt.hostSetId diff --git a/internal/db/schema/migrations/oss/postgres_26_01_test.go b/internal/db/schema/migrations/oss/postgres_26_01_test.go index 694f80970d..80aa3ac60c 100644 --- a/internal/db/schema/migrations/oss/postgres_26_01_test.go +++ b/internal/db/schema/migrations/oss/postgres_26_01_test.go @@ -183,13 +183,13 @@ values 'Expired', current_timestamp, current_timestamp) ` for _, a := range addresses { - _, err := rw.Exec(ctx, q, []interface{}{a.Address}) + _, err := rw.Exec(ctx, q, []any{a.Address}) require.NoError(t, err) } // Duplicate a few records... - _, err := rw.Exec(ctx, q, []interface{}{addresses[1].Address}) + _, err := rw.Exec(ctx, q, []any{addresses[1].Address}) require.NoError(t, err) - _, err = rw.Exec(ctx, q, []interface{}{addresses[5].Address}) + _, err = rw.Exec(ctx, q, []any{addresses[5].Address}) require.NoError(t, err) } diff --git a/internal/db/schema/migrations/oss/postgres_30_01_test.go b/internal/db/schema/migrations/oss/postgres_30_01_test.go index 075e363842..8f1e3dbb98 100644 --- a/internal/db/schema/migrations/oss/postgres_30_01_test.go +++ b/internal/db/schema/migrations/oss/postgres_30_01_test.go @@ -356,7 +356,7 @@ func loadCurrentDekVersions(t *testing.T, rw *db.Db) []dekVersion { require.NoError(t, err) require.NoError(t, err) for rows.Next() { - result := map[string]interface{}{} + result := map[string]any{} require.NoError(t, rw.ScanRows(context.Background(), rows, &result)) var v dekVersion switch versionType { diff --git a/internal/db/schema/migrations/oss/postgres_40_01_test.go b/internal/db/schema/migrations/oss/postgres_40_01_test.go index f842416e0a..07f0c662d8 100644 --- a/internal/db/schema/migrations/oss/postgres_40_01_test.go +++ b/internal/db/schema/migrations/oss/postgres_40_01_test.go @@ -85,7 +85,7 @@ insert into static_host_catalog (scope_id, public_id, name) values (?, ?, ?) -`, []interface{}{proj.GetPublicId(), hostCatalogId, "my-host-catalog"}) +`, []any{proj.GetPublicId(), hostCatalogId, "my-host-catalog"}) require.NoError(t, err) assert.Equal(t, 1, num) @@ -96,7 +96,7 @@ insert into static_host_set (public_id, catalog_id) values (?, ?) -`, []interface{}{hostSetId, hostCatalogId}) +`, []any{hostSetId, hostCatalogId}) require.NoError(t, err) assert.Equal(t, 1, num) @@ -107,7 +107,7 @@ insert into static_host (public_id, catalog_id, address) values (?, ?, ?) -`, []interface{}{hostId, hostCatalogId, "0.0.0.0"}) +`, []any{hostId, hostCatalogId, "0.0.0.0"}) require.NoError(t, err) assert.Equal(t, 1, num) @@ -117,7 +117,7 @@ insert into static_host_set_member (host_id, set_id) values (?, ?) -`, []interface{}{hostId, hostSetId}) +`, []any{hostId, hostSetId}) require.NoError(t, err) assert.Equal(t, 1, num) @@ -128,7 +128,7 @@ insert into target_tcp (public_id, scope_id, name, session_max_seconds, session_connection_limit) values (?, ?, ?, ?, ?); -`, []interface{}{targetId, proj.GetPublicId(), "my-credential-sources", 28800, -1}) +`, []any{targetId, proj.GetPublicId(), "my-credential-sources", 28800, -1}) require.NoError(t, err) assert.Equal(t, 1, num) @@ -139,7 +139,7 @@ insert into credential_vault_store (public_id, scope_id, vault_address) values (?, ?, ?); -`, []interface{}{vaultStoreId, proj.GetPublicId(), "http://vault"}) +`, []any{vaultStoreId, proj.GetPublicId(), "http://vault"}) require.NoError(t, err) assert.Equal(t, 1, num) @@ -154,7 +154,7 @@ insert into credential_static_store (public_id, scope_id, name) values (?, ?, ?) -`, []interface{}{staticStoreId, proj.GetPublicId(), "my-static-credential-store"}) +`, []any{staticStoreId, proj.GetPublicId(), "my-static-credential-store"}) require.NoError(t, err) assert.Equal(t, 1, num) @@ -171,9 +171,9 @@ values egressCred, err := target.NewStaticCredential(targetId, cred2.PublicId, "egress") require.NoError(t, err) - err = rw.CreateItems(ctx, []interface{}{appCredLib, egressCredLib}) + err = rw.CreateItems(ctx, []any{appCredLib, egressCredLib}) require.NoError(t, err) - err = rw.CreateItems(ctx, []interface{}{appCred, egressCred}) + err = rw.CreateItems(ctx, []any{appCred, egressCred}) require.NoError(t, err) dynCreds := []*session.DynamicCredential{ @@ -191,7 +191,7 @@ insert into target_host_set (target_id, host_set_id) values (?, ?) - `, []interface{}{targetId, hostSetId}) + `, []any{targetId, hostSetId}) require.NoError(t, err) assert.Equal(t, 1, num) @@ -206,7 +206,7 @@ values (public_id, user_id, host_id, target_id, host_set_id, auth_token_id, scope_id, certificate, expiration_time, endpoint) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `, []interface{}{sessionId, uId, hostId, targetId, hostSetId, at.GetPublicId(), proj.GetPublicId(), cert, expirationTime, "tcp://127.0.0.1:22"}) + `, []any{sessionId, uId, hostId, targetId, hostSetId, at.GetPublicId(), proj.GetPublicId(), cert, expirationTime, "tcp://127.0.0.1:22"}) require.NoError(t, err) assert.Equal(t, 1, num) @@ -216,7 +216,7 @@ insert into session_credential_dynamic values (?, ?, ?), (?, ?, ?); -`, []interface{}{ +`, []any{ sessionId, dynCreds[0].LibraryId, dynCreds[0].CredentialPurpose, sessionId, dynCreds[1].LibraryId, dynCreds[1].CredentialPurpose, }) @@ -229,7 +229,7 @@ insert into session_credential_static values (?, ?, ?), (?, ?, ?); -`, []interface{}{ +`, []any{ sessionId, staticCreds[0].CredentialStaticId, staticCreds[0].CredentialPurpose, sessionId, staticCreds[1].CredentialStaticId, staticCreds[1].CredentialPurpose, }) @@ -261,42 +261,42 @@ values // Validate migrations lookupLib := &target.CredentialLibrary{} - err = rw.LookupWhere(ctx, lookupLib, "credential_library_id = ?", []interface{}{appCredLib.GetCredentialLibraryId()}) + err = rw.LookupWhere(ctx, lookupLib, "credential_library_id = ?", []any{appCredLib.GetCredentialLibraryId()}) require.NoError(t, err) assert.Equal(t, "brokered", lookupLib.CredentialPurpose) lookupLib = &target.CredentialLibrary{} - err = rw.LookupWhere(ctx, lookupLib, "credential_library_id = ?", []interface{}{egressCredLib.GetCredentialLibraryId()}) + err = rw.LookupWhere(ctx, lookupLib, "credential_library_id = ?", []any{egressCredLib.GetCredentialLibraryId()}) require.NoError(t, err) assert.Equal(t, "injected_application", lookupLib.CredentialPurpose) lookupCred := &target.StaticCredential{} - err = rw.LookupWhere(ctx, lookupCred, "credential_static_id = ?", []interface{}{appCred.GetCredentialId()}) + err = rw.LookupWhere(ctx, lookupCred, "credential_static_id = ?", []any{appCred.GetCredentialId()}) require.NoError(t, err) assert.Equal(t, "brokered", lookupCred.CredentialPurpose) lookupCred = &target.StaticCredential{} - err = rw.LookupWhere(ctx, lookupCred, "credential_static_id = ?", []interface{}{egressCred.GetCredentialId()}) + err = rw.LookupWhere(ctx, lookupCred, "credential_static_id = ?", []any{egressCred.GetCredentialId()}) require.NoError(t, err) assert.Equal(t, "injected_application", lookupCred.CredentialPurpose) lookupDynCred := &session.DynamicCredential{} - err = rw.LookupWhere(ctx, lookupDynCred, "session_id = ? and library_id = ?", []interface{}{sessionId, appCredLib.GetCredentialLibraryId()}) + err = rw.LookupWhere(ctx, lookupDynCred, "session_id = ? and library_id = ?", []any{sessionId, appCredLib.GetCredentialLibraryId()}) require.NoError(t, err) assert.Equal(t, "brokered", lookupDynCred.CredentialPurpose) lookupDynCred = &session.DynamicCredential{} - err = rw.LookupWhere(ctx, lookupDynCred, "session_id = ? and library_id = ?", []interface{}{sessionId, egressCredLib.GetCredentialLibraryId()}) + err = rw.LookupWhere(ctx, lookupDynCred, "session_id = ? and library_id = ?", []any{sessionId, egressCredLib.GetCredentialLibraryId()}) require.NoError(t, err) assert.Equal(t, "injected_application", lookupDynCred.CredentialPurpose) lookupStaticCred := &session.StaticCredential{} - err = rw.LookupWhere(ctx, lookupStaticCred, "session_id = ? and credential_static_id = ?", []interface{}{sessionId, appCred.GetCredentialId()}) + err = rw.LookupWhere(ctx, lookupStaticCred, "session_id = ? and credential_static_id = ?", []any{sessionId, appCred.GetCredentialId()}) require.NoError(t, err) assert.Equal(t, "brokered", lookupStaticCred.CredentialPurpose) lookupStaticCred = &session.StaticCredential{} - err = rw.LookupWhere(ctx, lookupStaticCred, "session_id = ? and credential_static_id = ?", []interface{}{sessionId, egressCred.GetCredentialId()}) + err = rw.LookupWhere(ctx, lookupStaticCred, "session_id = ? and credential_static_id = ?", []any{sessionId, egressCred.GetCredentialId()}) require.NoError(t, err) assert.Equal(t, "injected_application", lookupStaticCred.CredentialPurpose) } diff --git a/internal/db/testing.go b/internal/db/testing.go index a0b29dd8fd..2b9dc66b8a 100644 --- a/internal/db/testing.go +++ b/internal/db/testing.go @@ -143,7 +143,7 @@ func AssertPublicId(t testing.TB, prefix, actual string) { // TestDeleteWhere allows you to easily delete resources for testing purposes // including all the current resources. -func TestDeleteWhere(t testing.TB, conn *DB, i interface{}, whereClause string, args ...interface{}) { +func TestDeleteWhere(t testing.TB, conn *DB, i any, whereClause string, args ...any) { t.Helper() require := require.New(t) ctx := context.Background() @@ -193,7 +193,7 @@ and create_time > NOW()::timestamp - (interval '1 second' * ?) } where := whereBase - whereArgs := []interface{}{ + whereArgs := []any{ whereKey, resourceId, } @@ -214,7 +214,7 @@ and create_time > NOW()::timestamp - (interval '1 second' * ?) } var foundEntry oplog.Entry - if err := r.LookupWhere(context.Background(), &foundEntry, "id = ?", []interface{}{metadata.EntryId}); err != nil { + if err := r.LookupWhere(context.Background(), &foundEntry, "id = ?", []any{metadata.EntryId}); err != nil { return err } return nil diff --git a/internal/db/timestamp/scanners.go b/internal/db/timestamp/scanners.go index 0cf43129a8..fbf7334750 100644 --- a/internal/db/timestamp/scanners.go +++ b/internal/db/timestamp/scanners.go @@ -15,7 +15,7 @@ var ( ) // Scan implements sql.Scanner for protobuf Timestamp. -func (ts *Timestamp) Scan(value interface{}) error { +func (ts *Timestamp) Scan(value any) error { switch t := value.(type) { case time.Time: ts.Timestamp = timestamppb.New(t) // google proto version diff --git a/internal/errors/error.go b/internal/errors/error.go index d505210d80..86a0e9b965 100644 --- a/internal/errors/error.go +++ b/internal/errors/error.go @@ -335,6 +335,6 @@ func Is(err, target error) bool { // As is the equivalent of the std errors.As, and allows devs to only import // this package for the capability. -func As(err error, target interface{}) bool { +func As(err error, target any) bool { return errors.As(err, target) } diff --git a/internal/errors/error_test.go b/internal/errors/error_test.go index 516258e32d..19dab3ac22 100644 --- a/internal/errors/error_test.go +++ b/internal/errors/error_test.go @@ -476,9 +476,9 @@ func TestConvertError(t *testing.T) { assert, require := assert.New(t), require.New(t) _, err := rw.Exec(ctx, truncateTable, nil) require.NoError(err) - _, err = rw.Exec(ctx, insert, []interface{}{"alice", "coworker", nil}) + _, err = rw.Exec(ctx, insert, []any{"alice", "coworker", nil}) require.NoError(err) - _, err = rw.Exec(ctx, insert, []interface{}{"alice", "dup coworker", nil}) + _, err = rw.Exec(ctx, insert, []any{"alice", "dup coworker", nil}) require.Error(err) e := errors.Convert(err) @@ -490,7 +490,7 @@ func TestConvertError(t *testing.T) { assert, require := assert.New(t), require.New(t) _, err := rw.Exec(ctx, truncateTable, nil) require.NoError(err) - _, err = rw.Exec(ctx, insert, []interface{}{"alice", nil, nil}) + _, err = rw.Exec(ctx, insert, []any{"alice", nil, nil}) require.Error(err) e := errors.Convert(err) @@ -502,7 +502,7 @@ func TestConvertError(t *testing.T) { assert, require := assert.New(t), require.New(t) _, err := rw.Exec(ctx, truncateTable, nil) require.NoError(err) - _, err = rw.Exec(ctx, insert, []interface{}{"alice", "coworker", "one"}) + _, err = rw.Exec(ctx, insert, []any{"alice", "coworker", "one"}) require.Error(err) e := errors.Convert(err) diff --git a/internal/errors/match.go b/internal/errors/match.go index bf98674b1d..6776a9e572 100644 --- a/internal/errors/match.go +++ b/internal/errors/match.go @@ -10,7 +10,7 @@ type Template struct { // T creates a new Template for matching Errs. Invalid parameters are ignored. // If more than is one parameter for a given type, only the last one is used. -func T(args ...interface{}) *Template { +func T(args ...any) *Template { t := &Template{} for _, a := range args { switch arg := a.(type) { diff --git a/internal/errors/match_test.go b/internal/errors/match_test.go index ff1819efe8..515e903a65 100644 --- a/internal/errors/match_test.go +++ b/internal/errors/match_test.go @@ -13,12 +13,12 @@ func TestT(t *testing.T) { stdErr := stderrors.New("test error") tests := []struct { name string - args []interface{} + args []any want *Template }{ { name: "all fields", - args: []interface{}{ + args: []any{ "test error msg", Op("alice.Bob"), InvalidParameter, @@ -37,7 +37,7 @@ func TestT(t *testing.T) { }, { name: "Kind only", - args: []interface{}{ + args: []any{ Integrity, }, want: &Template{ @@ -46,7 +46,7 @@ func TestT(t *testing.T) { }, { name: "multiple Kinds", - args: []interface{}{ + args: []any{ Search, Integrity, }, @@ -56,7 +56,7 @@ func TestT(t *testing.T) { }, { name: "ignore", - args: []interface{}{ + args: []any{ 32, }, want: &Template{}, diff --git a/internal/filter/filter_test.go b/internal/filter/filter_test.go index aacc5613de..993699e763 100644 --- a/internal/filter/filter_test.go +++ b/internal/filter/filter_test.go @@ -14,7 +14,7 @@ import ( func TestWellKnownTypeFilterHook(t *testing.T) { t.Run("wrappers", func(t *testing.T) { - conversions := map[interface{}]interface{}{ + conversions := map[any]any{ wrapperspb.String("foo"): "foo", wrapperspb.UInt64(123): uint64(123), wrapperspb.Int64(123): int64(123), @@ -39,12 +39,12 @@ func TestWellKnownTypeFilterHook(t *testing.T) { }) t.Run("struct", func(t *testing.T) { assert, require := assert.New(t), require.New(t) - s, err := structpb.NewStruct(map[string]interface{}{ + s, err := structpb.NewStruct(map[string]any{ "name": "test", }) require.NoError(err) - expect := map[string]interface{}{ + expect := map[string]any{ "name": "test", } actual := WellKnownTypeFilterHook(reflect.ValueOf(s)) diff --git a/internal/host/plugin/host_catalog_secret_test.go b/internal/host/plugin/host_catalog_secret_test.go index 146af909b9..487177ad70 100644 --- a/internal/host/plugin/host_catalog_secret_test.go +++ b/internal/host/plugin/host_catalog_secret_test.go @@ -66,7 +66,7 @@ func TestHostCatalogSecret_New(t *testing.T) { args: args{ catalogId: cat.GetPublicId(), attrs: func() *structpb.Struct { - st, err := structpb.NewStruct(map[string]interface{}{"foo": "bar"}) + st, err := structpb.NewStruct(map[string]any{"foo": "bar"}) require.NoError(t, err) return st }(), @@ -75,7 +75,7 @@ func TestHostCatalogSecret_New(t *testing.T) { HostCatalogSecret: &store.HostCatalogSecret{ CatalogId: cat.GetPublicId(), Secret: func() []byte { - st, err := structpb.NewStruct(map[string]interface{}{"foo": "bar"}) + st, err := structpb.NewStruct(map[string]any{"foo": "bar"}) require.NoError(t, err) b, err := proto.Marshal(st) require.NoError(t, err) @@ -128,7 +128,7 @@ func TestHostCatalogSecret_Create_Upsert_Update_Delete(t *testing.T) { cat := TestCatalog(t, conn, prj.GetPublicId(), plg.GetPublicId()) ctx := context.Background() - secret, err := newHostCatalogSecret(ctx, cat.GetPublicId(), mustStruct(map[string]interface{}{ + secret, err := newHostCatalogSecret(ctx, cat.GetPublicId(), mustStruct(map[string]any{ "foo": "bar", })) require.NoError(t, err) @@ -145,7 +145,7 @@ func TestHostCatalogSecret_Create_Upsert_Update_Delete(t *testing.T) { require.NoError(t, w.Create(ctx, secret)) // Upsert - newStructUpsert := mustMarshal(map[string]interface{}{ + newStructUpsert := mustMarshal(map[string]any{ "baz": "qux", }) newSecretUpsert := secret.clone() @@ -166,7 +166,7 @@ func TestHostCatalogSecret_Create_Upsert_Update_Delete(t *testing.T) { assert.Empty(t, cmp.Diff(newStructUpsert, found.Secret, protocmp.Transform())) // Update - newStructUpdate := mustMarshal(map[string]interface{}{ + newStructUpdate := mustMarshal(map[string]any{ "one": "two", }) newSecretUpdate := newSecretUpsert.clone() diff --git a/internal/host/plugin/host_catalog_test.go b/internal/host/plugin/host_catalog_test.go index 3e61722e6a..ad80cf58e7 100644 --- a/internal/host/plugin/host_catalog_test.go +++ b/internal/host/plugin/host_catalog_test.go @@ -368,7 +368,7 @@ func TestHostCatalog_SecretsHmac(t *testing.T) { { name: "valid", hcFn: func() *HostCatalog { - cat.Secrets = mustStruct(map[string]interface{}{"foo": "bar"}) + cat.Secrets = mustStruct(map[string]any{"foo": "bar"}) cat.SecretsHmac = nil return cat }, @@ -378,7 +378,7 @@ func TestHostCatalog_SecretsHmac(t *testing.T) { { name: "valid-different-val", hcFn: func() *HostCatalog { - cat.Secrets = mustStruct(map[string]interface{}{"zip": "zap"}) + cat.Secrets = mustStruct(map[string]any{"zip": "zap"}) cat.SecretsHmac = nil return cat }, @@ -387,7 +387,7 @@ func TestHostCatalog_SecretsHmac(t *testing.T) { { name: "valid-original-val", hcFn: func() *HostCatalog { - cat.Secrets = mustStruct(map[string]interface{}{"foo": "bar"}) + cat.Secrets = mustStruct(map[string]any{"foo": "bar"}) cat.SecretsHmac = nil return cat }, @@ -397,7 +397,7 @@ func TestHostCatalog_SecretsHmac(t *testing.T) { { name: "hmac-missing-wrapper", hcFn: func() *HostCatalog { - cat.Secrets = mustStruct(map[string]interface{}{"foo": "bar"}) + cat.Secrets = mustStruct(map[string]any{"foo": "bar"}) cat.SecretsHmac = []byte("foobar") return cat }, @@ -406,7 +406,7 @@ func TestHostCatalog_SecretsHmac(t *testing.T) { { name: "hmac-bad-wrapper", hcFn: func() *HostCatalog { - cat.Secrets = mustStruct(map[string]interface{}{"foo": "bar"}) + cat.Secrets = mustStruct(map[string]any{"foo": "bar"}) cat.SecretsHmac = nil return cat }, diff --git a/internal/host/plugin/job_set_sync.go b/internal/host/plugin/job_set_sync.go index 7071bf8956..51d2e4fa15 100644 --- a/internal/host/plugin/job_set_sync.go +++ b/internal/host/plugin/job_set_sync.go @@ -97,7 +97,7 @@ func (r *SetSyncJob) Run(ctx context.Context) error { // Fetch all sets that will reach their sync point within the syncWindow. // This is done to avoid constantly scheduling the set sync job when there // are multiple sets to sync in sequence. - err := r.reader.SearchWhere(ctx, &setAggs, setSyncJobQuery, []interface{}{-1 * setSyncJobRunInterval.Seconds()}, db.WithLimit(r.limit)) + err := r.reader.SearchWhere(ctx, &setAggs, setSyncJobQuery, []any{-1 * setSyncJobRunInterval.Seconds()}, db.WithLimit(r.limit)) if err != nil { return errors.Wrap(ctx, err, op) } @@ -144,7 +144,7 @@ func nextSync(ctx context.Context, j scheduler.Job) (time.Duration, error) { return 0, errors.NewDeprecated(errors.Unknown, op, "unknown job") } - rows, err := r.Query(context.Background(), query, []interface{}{setSyncJobRunInterval}) + rows, err := r.Query(context.Background(), query, []any{setSyncJobRunInterval}) if err != nil { return 0, errors.WrapDeprecated(err, op) } @@ -243,7 +243,7 @@ func (r *SetSyncJob) syncSets(ctx context.Context, setAggs []*hostSetAgg) error catIds = append(catIds, k) } var catAggs []*catalogAgg - if err := r.reader.SearchWhere(ctx, &catAggs, "public_id in (?)", []interface{}{catIds}); err != nil { + if err := r.reader.SearchWhere(ctx, &catAggs, "public_id in (?)", []any{catIds}); err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("can't retrieve catalogs %v", catIds))) } if len(catAggs) == 0 { @@ -544,7 +544,7 @@ func (r *SetSyncJob) upsertAndCleanHosts( } // Update last sync time - numRows, err := w.Exec(ctx, updateSyncDataQuery, []interface{}{setId}) + numRows, err := w.Exec(ctx, updateSyncDataQuery, []any{setId}) if err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg("updating last sync time")) } diff --git a/internal/host/plugin/loopback.go b/internal/host/plugin/loopback.go index f77b060ef6..81141c9f33 100644 --- a/internal/host/plugin/loopback.go +++ b/internal/host/plugin/loopback.go @@ -92,7 +92,7 @@ func (l *loopbackPlugin) onCreateSet(ctx context.Context, req *plgpb.OnCreateSet attrsMap := attrs.AsMap() if field := attrsMap[loopbackPluginHostInfoAttrField]; field != nil { switch t := field.(type) { - case []interface{}: + case []any: for _, h := range t { hostInfo := new(loopbackPluginHostInfo) if err := mapstructure.Decode(h, hostInfo); err != nil { @@ -100,7 +100,7 @@ func (l *loopbackPlugin) onCreateSet(ctx context.Context, req *plgpb.OnCreateSet } l.hostMap[set.GetId()] = append(l.hostMap[set.GetId()], hostInfo) } - case map[string]interface{}: + case map[string]any: hostInfo := new(loopbackPluginHostInfo) if err := mapstructure.Decode(t, hostInfo); err != nil { return nil, errors.Wrap(ctx, err, op) @@ -128,7 +128,7 @@ func (l *loopbackPlugin) onUpdateSet(ctx context.Context, req *plgpb.OnUpdateSet attrsMap := attrs.AsMap() if field := attrsMap[loopbackPluginHostInfoAttrField]; field != nil { switch t := field.(type) { - case []interface{}: + case []any: for _, h := range t { hostInfo := new(loopbackPluginHostInfo) if err := mapstructure.Decode(h, hostInfo); err != nil { @@ -136,7 +136,7 @@ func (l *loopbackPlugin) onUpdateSet(ctx context.Context, req *plgpb.OnUpdateSet } hosts = append(hosts, hostInfo) } - case map[string]interface{}: + case map[string]any: hostInfo := new(loopbackPluginHostInfo) if err := mapstructure.Decode(t, hostInfo); err != nil { return nil, errors.Wrap(ctx, err, op) diff --git a/internal/host/plugin/loopback_test.go b/internal/host/plugin/loopback_test.go index 2723e23554..5afcbba357 100644 --- a/internal/host/plugin/loopback_test.go +++ b/internal/host/plugin/loopback_test.go @@ -18,7 +18,7 @@ func TestLoopbackPlugin(t *testing.T) { ctx := context.Background() plg := NewLoopbackPlugin() - secretsMap := map[string]interface{}{ + secretsMap := map[string]any{ "key1": "key2", "baz": true, } @@ -38,7 +38,7 @@ func TestLoopbackPlugin(t *testing.T) { require.NotNil(catResp.GetPersisted().GetSecrets()) assert.EqualValues(secretsMap, catResp.GetPersisted().GetSecrets().AsMap()) - newSecretsMap := map[string]interface{}{ + newSecretsMap := map[string]any{ "key1": "key2", "baz": true, } @@ -63,12 +63,12 @@ func TestLoopbackPlugin(t *testing.T) { assert.EqualValues(newSecretsMap, upResp.GetPersisted().GetSecrets().AsMap()) // Add data to some sets - hostInfo1 := map[string]interface{}{ - loopbackPluginHostInfoAttrField: map[string]interface{}{ - "set_ids": []interface{}{"set1"}, + hostInfo1 := map[string]any{ + loopbackPluginHostInfoAttrField: map[string]any{ + "set_ids": []any{"set1"}, "external_id": "host1", - "ip_addresses": []interface{}{"1.2.3.4", "2.3.4.5"}, - "dns_names": []interface{}{"foo.com"}, + "ip_addresses": []any{"1.2.3.4", "2.3.4.5"}, + "dns_names": []any{"foo.com"}, }, } attrs, err := structpb.NewStruct(hostInfo1) @@ -82,12 +82,12 @@ func TestLoopbackPlugin(t *testing.T) { }, }) require.NoError(err) - hostInfo2 := map[string]interface{}{ - loopbackPluginHostInfoAttrField: map[string]interface{}{ - "set_ids": []interface{}{"set2"}, + hostInfo2 := map[string]any{ + loopbackPluginHostInfoAttrField: map[string]any{ + "set_ids": []any{"set2"}, "external_id": "host2", - "ip_addresses": []interface{}{"5.6.7.8", "6.7.8.9"}, - "dns_names": []interface{}{"bar.com"}, + "ip_addresses": []any{"5.6.7.8", "6.7.8.9"}, + "dns_names": []any{"bar.com"}, }, } attrs, err = structpb.NewStruct(hostInfo2) @@ -106,7 +106,7 @@ func TestLoopbackPlugin(t *testing.T) { type testInfo struct { name string sets []string - found []map[string]interface{} + found []map[string]any } validateSets := func(t *testing.T, tt testInfo) { require, assert := tr.New(t), ta.New(t) @@ -125,20 +125,20 @@ func TestLoopbackPlugin(t *testing.T) { require.Greater(len(resp.GetHosts()), 0) - var found []map[string]interface{} + var found []map[string]any for _, host := range resp.GetHosts() { - hostMap := map[string]interface{}{ + hostMap := map[string]any{ "external_id": host.GetExternalId(), } - var sets []interface{} + var sets []any for _, set := range host.SetIds { sets = append(sets, set) } - var ips []interface{} + var ips []any for _, ip := range host.GetIpAddresses() { ips = append(ips, ip) } - var names []interface{} + var names []any for _, name := range host.GetDnsNames() { names = append(names, name) } @@ -162,23 +162,23 @@ func TestLoopbackPlugin(t *testing.T) { { name: "set 1", sets: []string{"set1"}, - found: []map[string]interface{}{ - hostInfo1[loopbackPluginHostInfoAttrField].(map[string]interface{}), + found: []map[string]any{ + hostInfo1[loopbackPluginHostInfoAttrField].(map[string]any), }, }, { name: "set 2", sets: []string{"set2"}, - found: []map[string]interface{}{ - hostInfo2[loopbackPluginHostInfoAttrField].(map[string]interface{}), + found: []map[string]any{ + hostInfo2[loopbackPluginHostInfoAttrField].(map[string]any), }, }, { name: "sets 1 and 2", sets: []string{"set1", "set2"}, - found: []map[string]interface{}{ - hostInfo1[loopbackPluginHostInfoAttrField].(map[string]interface{}), - hostInfo2[loopbackPluginHostInfoAttrField].(map[string]interface{}), + found: []map[string]any{ + hostInfo1[loopbackPluginHostInfoAttrField].(map[string]any), + hostInfo2[loopbackPluginHostInfoAttrField].(map[string]any), }, }, } @@ -202,20 +202,20 @@ func TestLoopbackPlugin(t *testing.T) { { name: "set 1 deleted", sets: []string{"set1"}, - found: []map[string]interface{}{}, + found: []map[string]any{}, }, { name: "set 2 not deleted", sets: []string{"set2"}, - found: []map[string]interface{}{ - hostInfo2[loopbackPluginHostInfoAttrField].(map[string]interface{}), + found: []map[string]any{ + hostInfo2[loopbackPluginHostInfoAttrField].(map[string]any), }, }, { name: "sets 1 and 2 set 1 deleted", sets: []string{"set1", "set2"}, - found: []map[string]interface{}{ - hostInfo2[loopbackPluginHostInfoAttrField].(map[string]interface{}), + found: []map[string]any{ + hostInfo2[loopbackPluginHostInfoAttrField].(map[string]any), }, }, } @@ -233,19 +233,19 @@ func TestLoopbackPluginArrays(t *testing.T) { plg := NewLoopbackPlugin() // Add data to some sets - hostInfo1 := map[string]interface{}{ - loopbackPluginHostInfoAttrField: []interface{}{ - map[string]interface{}{ - "set_ids": []interface{}{"set1"}, + hostInfo1 := map[string]any{ + loopbackPluginHostInfoAttrField: []any{ + map[string]any{ + "set_ids": []any{"set1"}, "external_id": "host1a", - "ip_addresses": []interface{}{"1.2.3.4", "2.3.4.5"}, - "dns_names": []interface{}{"foo.com"}, + "ip_addresses": []any{"1.2.3.4", "2.3.4.5"}, + "dns_names": []any{"foo.com"}, }, - map[string]interface{}{ - "set_ids": []interface{}{"set1"}, + map[string]any{ + "set_ids": []any{"set1"}, "external_id": "host1b", - "ip_addresses": []interface{}{"3.4.5.6", "4.5.6.7"}, - "dns_names": []interface{}{"bar.com"}, + "ip_addresses": []any{"3.4.5.6", "4.5.6.7"}, + "dns_names": []any{"bar.com"}, }, }, } @@ -260,19 +260,19 @@ func TestLoopbackPluginArrays(t *testing.T) { }, }) require.NoError(err) - hostInfo2 := map[string]interface{}{ - loopbackPluginHostInfoAttrField: []interface{}{ - map[string]interface{}{ - "set_ids": []interface{}{"set2"}, + hostInfo2 := map[string]any{ + loopbackPluginHostInfoAttrField: []any{ + map[string]any{ + "set_ids": []any{"set2"}, "external_id": "host2a", - "ip_addresses": []interface{}{"10.20.30.40", "20.30.40.50"}, - "dns_names": []interface{}{"foz.com"}, + "ip_addresses": []any{"10.20.30.40", "20.30.40.50"}, + "dns_names": []any{"foz.com"}, }, - map[string]interface{}{ - "set_ids": []interface{}{"set2"}, + map[string]any{ + "set_ids": []any{"set2"}, "external_id": "host2b", - "ip_addresses": []interface{}{"30.40.50.60", "40.50.60.70"}, - "dns_names": []interface{}{"baz.com"}, + "ip_addresses": []any{"30.40.50.60", "40.50.60.70"}, + "dns_names": []any{"baz.com"}, }, }, } @@ -292,7 +292,7 @@ func TestLoopbackPluginArrays(t *testing.T) { type testInfo struct { name string sets []string - found []interface{} + found []any } validateSets := func(t *testing.T, tt testInfo) { require, assert := tr.New(t), ta.New(t) @@ -311,20 +311,20 @@ func TestLoopbackPluginArrays(t *testing.T) { require.Greater(len(resp.GetHosts()), 0) - var found []interface{} + var found []any for _, host := range resp.GetHosts() { - hostMap := map[string]interface{}{ + hostMap := map[string]any{ "external_id": host.GetExternalId(), } - var sets []interface{} + var sets []any for _, set := range host.SetIds { sets = append(sets, set) } - var ips []interface{} + var ips []any for _, ip := range host.GetIpAddresses() { ips = append(ips, ip) } - var names []interface{} + var names []any for _, name := range host.GetDnsNames() { names = append(names, name) } @@ -348,18 +348,18 @@ func TestLoopbackPluginArrays(t *testing.T) { { name: "set 1", sets: []string{"set1"}, - found: hostInfo1[loopbackPluginHostInfoAttrField].([]interface{}), + found: hostInfo1[loopbackPluginHostInfoAttrField].([]any), }, { name: "set 2", sets: []string{"set2"}, - found: hostInfo2[loopbackPluginHostInfoAttrField].([]interface{}), + found: hostInfo2[loopbackPluginHostInfoAttrField].([]any), }, { name: "sets 1 and 2", sets: []string{"set1", "set2"}, - found: append(hostInfo1[loopbackPluginHostInfoAttrField].([]interface{}), - hostInfo2[loopbackPluginHostInfoAttrField].([]interface{})...), + found: append(hostInfo1[loopbackPluginHostInfoAttrField].([]any), + hostInfo2[loopbackPluginHostInfoAttrField].([]any)...), }, } for _, tt := range setTests { diff --git a/internal/host/plugin/repository_host.go b/internal/host/plugin/repository_host.go index 5a01cdf10e..e323596b04 100644 --- a/internal/host/plugin/repository_host.go +++ b/internal/host/plugin/repository_host.go @@ -46,7 +46,7 @@ func (r *Repository) ListHostsByCatalogId(ctx context.Context, catalogId string, limit = opts.withLimit } var hostAggs []*hostAgg - err := r.reader.SearchWhere(ctx, &hostAggs, "catalog_id = ?", []interface{}{catalogId}, db.WithLimit(limit)) + err := r.reader.SearchWhere(ctx, &hostAggs, "catalog_id = ?", []any{catalogId}, db.WithLimit(limit)) switch { case err != nil: @@ -100,7 +100,7 @@ public_id in ` var hostAggs []*hostAgg - err := reader.SearchWhere(ctx, &hostAggs, query, []interface{}{setIds}, db.WithLimit(opts.withLimit)) + err := reader.SearchWhere(ctx, &hostAggs, query, []any{setIds}, db.WithLimit(opts.withLimit)) switch { case err != nil: diff --git a/internal/host/plugin/repository_host_catalog.go b/internal/host/plugin/repository_host_catalog.go index 8f8b7009c7..d122328ac1 100644 --- a/internal/host/plugin/repository_host_catalog.go +++ b/internal/host/plugin/repository_host_catalog.go @@ -602,7 +602,7 @@ func (r *Repository) ListCatalogs(ctx context.Context, projectIds []string, opt limit = opts.WithLimit } var hostCatalogs []*HostCatalog - if err := r.reader.SearchWhere(ctx, &hostCatalogs, "project_id in (?)", []interface{}{projectIds}, db.WithLimit(limit)); err != nil { + if err := r.reader.SearchWhere(ctx, &hostCatalogs, "project_id in (?)", []any{projectIds}, db.WithLimit(limit)); err != nil { return nil, nil, errors.Wrap(ctx, err, op) } plgIds := make([]string, 0, len(hostCatalogs)) @@ -610,7 +610,7 @@ func (r *Repository) ListCatalogs(ctx context.Context, projectIds []string, opt plgIds = append(plgIds, c.PluginId) } var plgs []*hostplugin.Plugin - if err := r.reader.SearchWhere(ctx, &plgs, "public_id in (?)", []interface{}{plgIds}); err != nil { + if err := r.reader.SearchWhere(ctx, &plgs, "public_id in (?)", []any{plgIds}); err != nil { return nil, nil, errors.Wrap(ctx, err, op) } return hostCatalogs, plgs, nil diff --git a/internal/host/plugin/repository_host_catalog_test.go b/internal/host/plugin/repository_host_catalog_test.go index a8115cb8c9..175f9c5f05 100644 --- a/internal/host/plugin/repository_host_catalog_test.go +++ b/internal/host/plugin/repository_host_catalog_test.go @@ -184,7 +184,7 @@ func TestRepository_CreateCatalog(t *testing.T) { ProjectId: prj.GetPublicId(), PluginId: plg.GetPublicId(), Attributes: func() []byte { - st, err := structpb.NewStruct(map[string]interface{}{ + st, err := structpb.NewStruct(map[string]any{ "k1": "foo", "nilkey": nil, normalizeToSliceKey: "normalizeme", @@ -201,7 +201,7 @@ func TestRepository_CreateCatalog(t *testing.T) { ProjectId: prj.GetPublicId(), PluginId: plg.GetPublicId(), Attributes: func() []byte { - st, err := structpb.NewStruct(map[string]interface{}{"k1": "foo"}) + st, err := structpb.NewStruct(map[string]any{"k1": "foo"}) require.NoError(t, err) b, err := proto.Marshal(st) require.NoError(t, err) @@ -221,7 +221,7 @@ func TestRepository_CreateCatalog(t *testing.T) { Attributes: []byte{}, }, Secrets: func() *structpb.Struct { - st, err := structpb.NewStruct(map[string]interface{}{ + st, err := structpb.NewStruct(map[string]any{ "k1": "v1", "k2": 2, "k3": nil, @@ -239,7 +239,7 @@ func TestRepository_CreateCatalog(t *testing.T) { }, }, wantSecret: func() *structpb.Struct { - st, err := structpb.NewStruct(map[string]interface{}{ + st, err := structpb.NewStruct(map[string]any{ "k1": "v1", "k2": 2, "k3": nil, @@ -343,7 +343,7 @@ func TestRepository_CreateCatalog(t *testing.T) { assert.NoError(db.TestVerifyOplog(t, rw, got.PublicId, db.WithOperation(oplog.OpType_OP_TYPE_CREATE), db.WithCreateNotBefore(10*time.Second))) cSecret := allocHostCatalogSecret() - err = rw.LookupWhere(ctx, &cSecret, "catalog_id=?", []interface{}{got.GetPublicId()}) + err = rw.LookupWhere(ctx, &cSecret, "catalog_id=?", []any{got.GetPublicId()}) if tt.wantSecret == nil { assert.Nil(got.Secrets) require.Error(err) @@ -571,14 +571,14 @@ func TestRepository_UpdateCatalog(t *testing.T) { } } - changeAttributes := func(m map[string]interface{}) changeHostCatalogFunc { + changeAttributes := func(m map[string]any) changeHostCatalogFunc { return func(c *HostCatalog) *HostCatalog { c.Attributes = mustMarshal(m) return c } } - changeSecrets := func(m map[string]interface{}) changeHostCatalogFunc { + changeSecrets := func(m map[string]any) changeHostCatalogFunc { return func(c *HostCatalog) *HostCatalog { c.Secrets = mustStruct(m) return c @@ -650,7 +650,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { } } - checkAttributes := func(want map[string]interface{}) checkFunc { + checkAttributes := func(want map[string]any) checkFunc { return func(t *testing.T, ctx context.Context) { t.Helper() assert := assert.New(t) @@ -662,14 +662,14 @@ func TestRepository_UpdateCatalog(t *testing.T) { } } - checkSecrets := func(want map[string]interface{}) checkFunc { + checkSecrets := func(want map[string]any) checkFunc { return func(t *testing.T, ctx context.Context) { t.Helper() assert := assert.New(t) require := require.New(t) cSecret := allocHostCatalogSecret() - err := dbRW.LookupWhere(ctx, &cSecret, "catalog_id=?", []interface{}{gotCatalog.GetPublicId()}) + err := dbRW.LookupWhere(ctx, &cSecret, "catalog_id=?", []any{gotCatalog.GetPublicId()}) require.NoError(err) require.Empty(cSecret.Secret) require.NotEmpty(cSecret.CtSecret) @@ -690,7 +690,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { assert := assert.New(t) cSecret := allocHostCatalogSecret() - err := dbRW.LookupWhere(ctx, &cSecret, "catalog_id=?", []interface{}{gotCatalog.GetPublicId()}) + err := dbRW.LookupWhere(ctx, &cSecret, "catalog_id=?", []any{gotCatalog.GetPublicId()}) assert.Error(err) assert.True(errors.IsNotFoundError(err)) } @@ -744,7 +744,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { } } - checkUpdateCatalogRequestCurrentAttributes := func(want map[string]interface{}) checkFunc { + checkUpdateCatalogRequestCurrentAttributes := func(want map[string]any) checkFunc { return func(t *testing.T, ctx context.Context) { t.Helper() assert := assert.New(t) @@ -752,7 +752,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { } } - checkUpdateCatalogRequestNewAttributes := func(want map[string]interface{}) checkFunc { + checkUpdateCatalogRequestNewAttributes := func(want map[string]any) checkFunc { return func(t *testing.T, ctx context.Context) { t.Helper() assert := assert.New(t) @@ -760,7 +760,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { } } - checkUpdateCatalogRequestPersistedSecrets := func(want map[string]interface{}) checkFunc { + checkUpdateCatalogRequestPersistedSecrets := func(want map[string]any) checkFunc { return func(t *testing.T, ctx context.Context) { t.Helper() assert := assert.New(t) @@ -768,7 +768,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { } } - checkUpdateCatalogRequestSecrets := func(want map[string]interface{}) checkFunc { + checkUpdateCatalogRequestSecrets := func(want map[string]any) checkFunc { return func(t *testing.T, ctx context.Context) { t.Helper() assert := assert.New(t) @@ -883,7 +883,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { checkUpdateCatalogRequestCurrentNameNil(), checkUpdateCatalogRequestNewName("foo"), checkName("foo"), - checkSecrets(map[string]interface{}{ + checkSecrets(map[string]any{ "one": "two", }), checkNumUpdated(1), @@ -901,7 +901,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { checkUpdateCatalogRequestCurrentNameNil(), checkUpdateCatalogRequestNewNameNil(), checkName(""), - checkSecrets(map[string]interface{}{ + checkSecrets(map[string]any{ "one": "two", }), checkNumUpdated(1), @@ -919,7 +919,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { checkUpdateCatalogRequestCurrentNameNil(), checkUpdateCatalogRequestNewName(testDuplicateCatalogNameAltScope), checkName(testDuplicateCatalogNameAltScope), - checkSecrets(map[string]interface{}{ + checkSecrets(map[string]any{ "one": "two", }), checkNumUpdated(1), @@ -937,7 +937,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { checkUpdateCatalogRequestCurrentDescriptionNil(), checkUpdateCatalogRequestNewDescription("foo"), checkDescription("foo"), - checkSecrets(map[string]interface{}{ + checkSecrets(map[string]any{ "one": "two", }), checkNumUpdated(1), @@ -955,7 +955,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { checkUpdateCatalogRequestCurrentDescriptionNil(), checkUpdateCatalogRequestNewDescriptionNil(), checkDescription(""), - checkSecrets(map[string]interface{}{ + checkSecrets(map[string]any{ "one": "two", }), checkNumUpdated(1), @@ -964,7 +964,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { }, { name: "update attributes (add)", - changeFuncs: []changeHostCatalogFunc{changeAttributes(map[string]interface{}{ + changeFuncs: []changeHostCatalogFunc{changeAttributes(map[string]any{ "baz": "qux", })}, version: 2, @@ -972,18 +972,18 @@ func TestRepository_UpdateCatalog(t *testing.T) { wantCheckFuncs: []checkFunc{ checkVersion(3), checkSecretsHmac(true), - checkUpdateCatalogRequestCurrentAttributes(map[string]interface{}{ + checkUpdateCatalogRequestCurrentAttributes(map[string]any{ "foo": "bar", }), - checkUpdateCatalogRequestNewAttributes(map[string]interface{}{ + checkUpdateCatalogRequestNewAttributes(map[string]any{ "foo": "bar", "baz": "qux", }), - checkAttributes(map[string]interface{}{ + checkAttributes(map[string]any{ "foo": "bar", "baz": "qux", }), - checkSecrets(map[string]interface{}{ + checkSecrets(map[string]any{ "one": "two", }), checkNumUpdated(1), @@ -992,7 +992,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { }, { name: "update attributes (overwrite)", - changeFuncs: []changeHostCatalogFunc{changeAttributes(map[string]interface{}{ + changeFuncs: []changeHostCatalogFunc{changeAttributes(map[string]any{ "foo": "baz", normalizeToSliceKey: "normalizeme", })}, @@ -1001,18 +1001,18 @@ func TestRepository_UpdateCatalog(t *testing.T) { wantCheckFuncs: []checkFunc{ checkVersion(3), checkSecretsHmac(true), - checkUpdateCatalogRequestCurrentAttributes(map[string]interface{}{ + checkUpdateCatalogRequestCurrentAttributes(map[string]any{ "foo": "bar", }), - checkUpdateCatalogRequestNewAttributes(map[string]interface{}{ + checkUpdateCatalogRequestNewAttributes(map[string]any{ "foo": "baz", normalizeToSliceKey: []any{"normalizeme"}, }), - checkAttributes(map[string]interface{}{ + checkAttributes(map[string]any{ "foo": "baz", normalizeToSliceKey: []any{"normalizeme"}, }), - checkSecrets(map[string]interface{}{ + checkSecrets(map[string]any{ "one": "two", }), checkNumUpdated(1), @@ -1021,7 +1021,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { }, { name: "update attributes (null)", - changeFuncs: []changeHostCatalogFunc{changeAttributes(map[string]interface{}{ + changeFuncs: []changeHostCatalogFunc{changeAttributes(map[string]any{ "foo": nil, })}, version: 2, @@ -1029,12 +1029,12 @@ func TestRepository_UpdateCatalog(t *testing.T) { wantCheckFuncs: []checkFunc{ checkVersion(3), checkSecretsHmac(true), - checkUpdateCatalogRequestCurrentAttributes(map[string]interface{}{ + checkUpdateCatalogRequestCurrentAttributes(map[string]any{ "foo": "bar", }), - checkUpdateCatalogRequestNewAttributes(map[string]interface{}{}), - checkAttributes(map[string]interface{}{}), - checkSecrets(map[string]interface{}{ + checkUpdateCatalogRequestNewAttributes(map[string]any{}), + checkAttributes(map[string]any{}), + checkSecrets(map[string]any{ "one": "two", }), checkNumUpdated(1), @@ -1043,7 +1043,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { }, { name: "update attributes (combined)", - changeFuncs: []changeHostCatalogFunc{changeAttributes(map[string]interface{}{ + changeFuncs: []changeHostCatalogFunc{changeAttributes(map[string]any{ "a": "b", "foo": "baz", })}, @@ -1052,18 +1052,18 @@ func TestRepository_UpdateCatalog(t *testing.T) { wantCheckFuncs: []checkFunc{ checkVersion(3), checkSecretsHmac(true), - checkUpdateCatalogRequestCurrentAttributes(map[string]interface{}{ + checkUpdateCatalogRequestCurrentAttributes(map[string]any{ "foo": "bar", }), - checkUpdateCatalogRequestNewAttributes(map[string]interface{}{ + checkUpdateCatalogRequestNewAttributes(map[string]any{ "a": "b", "foo": "baz", }), - checkAttributes(map[string]interface{}{ + checkAttributes(map[string]any{ "a": "b", "foo": "baz", }), - checkSecrets(map[string]interface{}{ + checkSecrets(map[string]any{ "one": "two", }), checkNumUpdated(1), @@ -1072,7 +1072,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { }, { name: "update secrets", - changeFuncs: []changeHostCatalogFunc{changeSecrets(map[string]interface{}{ + changeFuncs: []changeHostCatalogFunc{changeSecrets(map[string]any{ "three": "four", "five": "six", })}, @@ -1081,14 +1081,14 @@ func TestRepository_UpdateCatalog(t *testing.T) { wantCheckFuncs: []checkFunc{ checkVersion(3), checkSecretsHmac(true), - checkUpdateCatalogRequestPersistedSecrets(map[string]interface{}{ + checkUpdateCatalogRequestPersistedSecrets(map[string]any{ "one": "two", }), - checkUpdateCatalogRequestSecrets(map[string]interface{}{ + checkUpdateCatalogRequestSecrets(map[string]any{ "three": "four", "five": "six", }), - checkSecrets(map[string]interface{}{ + checkSecrets(map[string]any{ "three": "four", "five": "six", }), @@ -1099,7 +1099,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { { name: "update secrets, return nil secrets from plugin", withRespSecretsNil: true, - changeFuncs: []changeHostCatalogFunc{changeSecrets(map[string]interface{}{ + changeFuncs: []changeHostCatalogFunc{changeSecrets(map[string]any{ "three": "four", })}, version: 2, @@ -1107,13 +1107,13 @@ func TestRepository_UpdateCatalog(t *testing.T) { wantCheckFuncs: []checkFunc{ checkVersion(3), // incremented due to secrets_hmac checkSecretsHmac(true), - checkUpdateCatalogRequestPersistedSecrets(map[string]interface{}{ + checkUpdateCatalogRequestPersistedSecrets(map[string]any{ "one": "two", }), - checkUpdateCatalogRequestSecrets(map[string]interface{}{ + checkUpdateCatalogRequestSecrets(map[string]any{ "three": "four", }), - checkSecrets(map[string]interface{}{ + checkSecrets(map[string]any{ "one": "two", }), checkNumUpdated(1), @@ -1121,16 +1121,16 @@ func TestRepository_UpdateCatalog(t *testing.T) { }, { name: "delete secrets", - changeFuncs: []changeHostCatalogFunc{changeSecrets(map[string]interface{}{})}, + changeFuncs: []changeHostCatalogFunc{changeSecrets(map[string]any{})}, version: 2, fieldMask: []string{"secrets"}, wantCheckFuncs: []checkFunc{ checkVersion(3), checkSecretsHmac(false), - checkUpdateCatalogRequestPersistedSecrets(map[string]interface{}{ + checkUpdateCatalogRequestPersistedSecrets(map[string]any{ "one": "two", }), - checkUpdateCatalogRequestSecrets(map[string]interface{}{}), + checkUpdateCatalogRequestSecrets(map[string]any{}), checkSecretsDeleted(), checkNumUpdated(1), checkVerifyCatalogOplog(oplog.OpType_OP_TYPE_UPDATE), @@ -1140,7 +1140,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { name: "update name and secrets", changeFuncs: []changeHostCatalogFunc{ changeName("foo"), - changeSecrets(map[string]interface{}{ + changeSecrets(map[string]any{ "three": "four", }), }, @@ -1151,11 +1151,11 @@ func TestRepository_UpdateCatalog(t *testing.T) { checkSecretsHmac(true), checkUpdateCatalogRequestCurrentNameNil(), checkUpdateCatalogRequestNewName("foo"), - checkUpdateCatalogRequestSecrets(map[string]interface{}{ + checkUpdateCatalogRequestSecrets(map[string]any{ "three": "four", }), checkName("foo"), - checkSecrets(map[string]interface{}{ + checkSecrets(map[string]any{ "three": "four", }), checkNumUpdated(1), @@ -1176,7 +1176,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { // Set up some secrets scopeWrapper, err := dbKmsCache.GetWrapper(ctx, cat.GetProjectId(), kms.KeyPurposeDatabase) require.NoError(err) - cat.Secrets = mustStruct(map[string]interface{}{ + cat.Secrets = mustStruct(map[string]any{ "one": "two", }) require.NoError(cat.hmacSecrets(ctx, scopeWrapper)) @@ -1187,7 +1187,7 @@ func TestRepository_UpdateCatalog(t *testing.T) { require.NoError(err) // Set some (default) attributes on our test catalog and update SecretsHmac at the same time - cat.Attributes = mustMarshal(map[string]interface{}{ + cat.Attributes = mustMarshal(map[string]any{ "foo": "bar", }) numCatUpdated, err := dbRW.Update(ctx, cat, []string{"attributes", "SecretsHmac"}, []string{}) @@ -1575,7 +1575,7 @@ func TestRepository_UpdateCatalog_SyncSets(t *testing.T) { require.NotNil(t, repo) // Updating an empty catalog should not trigger an update. - emptyTestCatalog.Attributes = mustMarshal(map[string]interface{}{"foo": "bar"}) + emptyTestCatalog.Attributes = mustMarshal(map[string]any{"foo": "bar"}) var catalogsUpdated int _, _, catalogsUpdated, err = repo.UpdateCatalog(ctx, emptyTestCatalog, emptyTestCatalog.Version, []string{"attributes"}) require.NoError(t, err) @@ -1612,7 +1612,7 @@ func TestRepository_UpdateCatalog_SyncSets(t *testing.T) { require.GreaterOrEqual(t, time.Until(jj.GetNextScheduledRun().GetTimestamp().AsTime()), time.Second) // Updating attributes should trigger update - testCatalog.Attributes = mustMarshal(map[string]interface{}{"foo": "bar"}) + testCatalog.Attributes = mustMarshal(map[string]any{"foo": "bar"}) _, _, catalogsUpdated, err = repo.UpdateCatalog(ctx, testCatalog, testCatalog.Version, []string{"attributes"}) require.NoError(t, err) require.Equal(t, 1, catalogsUpdated) @@ -1644,7 +1644,7 @@ func assertPluginBasedPublicId(t *testing.T, prefix, actual string) { // mustStruct creates a structpb.Struct, and panics if there is an // error. -func mustStruct(in map[string]interface{}) *structpb.Struct { +func mustStruct(in map[string]any) *structpb.Struct { out, err := structpb.NewStruct(in) if err != nil { panic(err) @@ -1655,7 +1655,7 @@ func mustStruct(in map[string]interface{}) *structpb.Struct { // mustMarshal behaves like mustStruct but also converts the Struct // to wire-format data. -func mustMarshal(in map[string]interface{}) []byte { +func mustMarshal(in map[string]any) []byte { b, err := proto.Marshal(mustStruct(in)) if err != nil { panic(err) diff --git a/internal/host/plugin/repository_host_set.go b/internal/host/plugin/repository_host_set.go index 3bca396c4d..ead26c7b24 100644 --- a/internal/host/plugin/repository_host_set.go +++ b/internal/host/plugin/repository_host_set.go @@ -131,9 +131,9 @@ func (r *Repository) CreateSet(ctx context.Context, projectId string, s *HostSet } } - var preferredEndpoints []interface{} + var preferredEndpoints []any if s.PreferredEndpoints != nil { - preferredEndpoints = make([]interface{}, 0, len(s.PreferredEndpoints)) + preferredEndpoints = make([]any, 0, len(s.PreferredEndpoints)) for i, e := range s.PreferredEndpoints { obj, err := host.NewPreferredEndpoint(ctx, s.PublicId, uint32(i+1), e) if err != nil { @@ -385,9 +385,9 @@ func (r *Repository) UpdateSet(ctx context.Context, projectId string, s *HostSet } // Get the preferred endpoints to write out. - var preferredEndpoints []interface{} + var preferredEndpoints []any if endpointOp == endpointOpUpdate { - preferredEndpoints = make([]interface{}, 0, len(newSet.PreferredEndpoints)) + preferredEndpoints = make([]any, 0, len(newSet.PreferredEndpoints)) for i, e := range newSet.PreferredEndpoints { obj, err := host.NewPreferredEndpoint(ctx, newSet.PublicId, uint32(i+1), e) if err != nil { @@ -447,7 +447,7 @@ func (r *Repository) UpdateSet(ctx context.Context, projectId string, s *HostSet case endpointOpDelete, endpointOpUpdate: if len(currentSet.PreferredEndpoints) > 0 { // Delete all old endpoint entries. - var peps []interface{} + var peps []any for i := 1; i <= len(currentSet.PreferredEndpoints); i++ { p := host.AllocPreferredEndpoint() p.HostSetId, p.Priority = currentSet.GetPublicId(), uint32(i) @@ -700,7 +700,7 @@ func (r *Repository) getSets(ctx context.Context, publicId string, catalogId str limit = opts.WithLimit } - args := make([]interface{}, 0, 1) + args := make([]any, 0, 1) var where string switch { @@ -794,7 +794,7 @@ func (r *Repository) Endpoints(ctx context.Context, setIds []string) ([]*host.En // Fist, look up the sets corresponding to the set IDs var setAggs []*hostSetAgg - if err := r.reader.SearchWhere(ctx, &setAggs, "public_id in (?)", []interface{}{setIds}); err != nil { + if err := r.reader.SearchWhere(ctx, &setAggs, "public_id in (?)", []any{setIds}); err != nil { return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("can't retrieve sets %v", setIds))) } if len(setAggs) == 0 { @@ -810,7 +810,7 @@ func (r *Repository) Endpoints(ctx context.Context, setIds []string) ([]*host.En } var setMembers []*HostSetMember - if err := r.reader.SearchWhere(ctx, &setMembers, "set_id in (?)", []interface{}{setIds}); err != nil { + if err := r.reader.SearchWhere(ctx, &setMembers, "set_id in (?)", []any{setIds}); err != nil { return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("can't retrieve set members for sets %v", setIds))) } if len(setMembers) == 0 { @@ -826,7 +826,7 @@ func (r *Repository) Endpoints(ctx context.Context, setIds []string) ([]*host.En hostIds = append(hostIds, hid) } var hostAggs []*hostAgg - if err := r.reader.SearchWhere(ctx, &hostAggs, "public_id in (?)", []interface{}{hostIds}); err != nil { + if err := r.reader.SearchWhere(ctx, &hostAggs, "public_id in (?)", []any{hostIds}); err != nil { return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("can't retrieve hosts %v", hostIds))) } if len(hostAggs) == 0 { diff --git a/internal/host/plugin/repository_host_set_test.go b/internal/host/plugin/repository_host_set_test.go index b3918ba96f..53562741e8 100644 --- a/internal/host/plugin/repository_host_set_test.go +++ b/internal/host/plugin/repository_host_set_test.go @@ -236,7 +236,7 @@ func TestRepository_CreateSet(t *testing.T) { CatalogId: catalog.PublicId, Description: ("test-description-repo"), Attributes: func() []byte { - st, err := structpb.NewStruct(map[string]interface{}{ + st, err := structpb.NewStruct(map[string]any{ "k1": "foo", "removed": nil, normalizeToSliceKey: "normalizeme", @@ -462,7 +462,7 @@ func TestRepository_UpdateSet(t *testing.T) { // Set up a test catalog and the secrets for it testCatalog := TestCatalog(t, dbConn, projectScope.PublicId, testPlugin.GetPublicId()) - testCatalogSecret, err := newHostCatalogSecret(ctx, testCatalog.GetPublicId(), mustStruct(map[string]interface{}{ + testCatalogSecret, err := newHostCatalogSecret(ctx, testCatalog.GetPublicId(), mustStruct(map[string]any{ "one": "two", })) require.NoError(t, err) @@ -535,7 +535,7 @@ func TestRepository_UpdateSet(t *testing.T) { } } - changeAttributes := func(m map[string]interface{}) changeHostSetFunc { + changeAttributes := func(m map[string]any) changeHostSetFunc { return func(c *HostSet) *HostSet { c.Attributes = mustMarshal(m) return c @@ -589,7 +589,7 @@ func TestRepository_UpdateSet(t *testing.T) { } } - checkAttributes := func(want map[string]interface{}) checkHostSetFunc { + checkAttributes := func(want map[string]any) checkHostSetFunc { return func(t *testing.T, got *HostSet) { t.Helper() st := &structpb.Struct{} @@ -692,21 +692,21 @@ func TestRepository_UpdateSet(t *testing.T) { } } - checkUpdateSetRequestCurrentAttributes := func(want map[string]interface{}) checkPluginReqFunc { + checkUpdateSetRequestCurrentAttributes := func(want map[string]any) checkPluginReqFunc { return func(t *testing.T, got *plgpb.OnUpdateSetRequest) { t.Helper() assert.Empty(t, cmp.Diff(mustStruct(want), got.CurrentSet.GetAttributes(), protocmp.Transform()), "checkUpdateSetRequestCurrentAttributes") } } - checkUpdateSetRequestNewAttributes := func(want map[string]interface{}) checkPluginReqFunc { + checkUpdateSetRequestNewAttributes := func(want map[string]any) checkPluginReqFunc { return func(t *testing.T, got *plgpb.OnUpdateSetRequest) { t.Helper() assert.Empty(t, cmp.Diff(mustStruct(want), got.NewSet.GetAttributes(), protocmp.Transform()), "checkUpdateSetRequestNewAttributes") } } - checkUpdateSetRequestPersistedSecrets := func(want map[string]interface{}) checkPluginReqFunc { + checkUpdateSetRequestPersistedSecrets := func(want map[string]any) checkPluginReqFunc { return func(t *testing.T, got *plgpb.OnUpdateSetRequest) { t.Helper() assert.Empty(t, cmp.Diff(mustStruct(want), got.Persisted.Secrets, protocmp.Transform()), "checkUpdateSetRequestPersistedSecrets") @@ -760,7 +760,7 @@ func TestRepository_UpdateSet(t *testing.T) { WithPreferredEndpoints([]string{"cidr:192.168.0.0/24", "cidr:192.168.1.0/24", "cidr:172.16.0.0/12"}), ) // Set some (default) attributes on our test set - set.Attributes = mustMarshal(map[string]interface{}{ + set.Attributes = mustMarshal(map[string]any{ "foo": "bar", }) @@ -880,7 +880,7 @@ func TestRepository_UpdateSet(t *testing.T) { wantCheckPluginReqFuncs: []checkPluginReqFunc{ checkUpdateSetRequestCurrentNameNil(), checkUpdateSetRequestNewName("foo"), - checkUpdateSetRequestPersistedSecrets(map[string]interface{}{ + checkUpdateSetRequestPersistedSecrets(map[string]any{ "one": "two", }), }, @@ -899,7 +899,7 @@ func TestRepository_UpdateSet(t *testing.T) { wantCheckPluginReqFuncs: []checkPluginReqFunc{ checkUpdateSetRequestCurrentNameNil(), checkUpdateSetRequestNewNameNil(), - checkUpdateSetRequestPersistedSecrets(map[string]interface{}{ + checkUpdateSetRequestPersistedSecrets(map[string]any{ "one": "two", }), }, @@ -918,7 +918,7 @@ func TestRepository_UpdateSet(t *testing.T) { wantCheckPluginReqFuncs: []checkPluginReqFunc{ checkUpdateSetRequestCurrentDescriptionNil(), checkUpdateSetRequestNewDescription("foo"), - checkUpdateSetRequestPersistedSecrets(map[string]interface{}{ + checkUpdateSetRequestPersistedSecrets(map[string]any{ "one": "two", }), }, @@ -937,7 +937,7 @@ func TestRepository_UpdateSet(t *testing.T) { wantCheckPluginReqFuncs: []checkPluginReqFunc{ checkUpdateSetRequestCurrentDescriptionNil(), checkUpdateSetRequestNewDescriptionNil(), - checkUpdateSetRequestPersistedSecrets(map[string]interface{}{ + checkUpdateSetRequestPersistedSecrets(map[string]any{ "one": "two", }), }, @@ -954,7 +954,7 @@ func TestRepository_UpdateSet(t *testing.T) { changeFuncs: []changeHostSetFunc{changeSyncInterval(42)}, fieldMask: []string{"SyncIntervalSeconds"}, wantCheckPluginReqFuncs: []checkPluginReqFunc{ - checkUpdateSetRequestPersistedSecrets(map[string]interface{}{ + checkUpdateSetRequestPersistedSecrets(map[string]any{ "one": "two", }), }, @@ -973,7 +973,7 @@ func TestRepository_UpdateSet(t *testing.T) { wantCheckPluginReqFuncs: []checkPluginReqFunc{ checkUpdateSetRequestCurrentPreferredEndpoints(nil), checkUpdateSetRequestNewPreferredEndpoints([]string{"cidr:10.0.0.0/24"}), - checkUpdateSetRequestPersistedSecrets(map[string]interface{}{ + checkUpdateSetRequestPersistedSecrets(map[string]any{ "one": "two", }), }, @@ -992,7 +992,7 @@ func TestRepository_UpdateSet(t *testing.T) { wantCheckPluginReqFuncs: []checkPluginReqFunc{ checkUpdateSetRequestCurrentPreferredEndpoints([]string{"cidr:192.168.0.0/24", "cidr:192.168.1.0/24", "cidr:172.16.0.0/12"}), checkUpdateSetRequestNewPreferredEndpoints([]string{"cidr:10.0.0.0/24"}), - checkUpdateSetRequestPersistedSecrets(map[string]interface{}{ + checkUpdateSetRequestPersistedSecrets(map[string]any{ "one": "two", }), }, @@ -1011,7 +1011,7 @@ func TestRepository_UpdateSet(t *testing.T) { wantCheckPluginReqFuncs: []checkPluginReqFunc{ checkUpdateSetRequestCurrentPreferredEndpoints([]string{"cidr:192.168.0.0/24", "cidr:192.168.1.0/24", "cidr:172.16.0.0/12"}), checkUpdateSetRequestNewPreferredEndpointsNil(), - checkUpdateSetRequestPersistedSecrets(map[string]interface{}{ + checkUpdateSetRequestPersistedSecrets(map[string]any{ "one": "two", }), }, @@ -1024,25 +1024,25 @@ func TestRepository_UpdateSet(t *testing.T) { { name: "update attributes (add)", startingSet: setupHostSet, - changeFuncs: []changeHostSetFunc{changeAttributes(map[string]interface{}{ + changeFuncs: []changeHostSetFunc{changeAttributes(map[string]any{ "baz": "qux", })}, fieldMask: []string{"attributes"}, wantCheckPluginReqFuncs: []checkPluginReqFunc{ - checkUpdateSetRequestCurrentAttributes(map[string]interface{}{ + checkUpdateSetRequestCurrentAttributes(map[string]any{ "foo": "bar", }), - checkUpdateSetRequestNewAttributes(map[string]interface{}{ + checkUpdateSetRequestNewAttributes(map[string]any{ "foo": "bar", "baz": "qux", }), - checkUpdateSetRequestPersistedSecrets(map[string]interface{}{ + checkUpdateSetRequestPersistedSecrets(map[string]any{ "one": "two", }), }, wantCheckSetFuncs: []checkHostSetFunc{ checkVersion(3), - checkAttributes(map[string]interface{}{ + checkAttributes(map[string]any{ "foo": "bar", "baz": "qux", }), @@ -1053,26 +1053,26 @@ func TestRepository_UpdateSet(t *testing.T) { { name: "update attributes (overwrite)", startingSet: setupHostSet, - changeFuncs: []changeHostSetFunc{changeAttributes(map[string]interface{}{ + changeFuncs: []changeHostSetFunc{changeAttributes(map[string]any{ "foo": "baz", normalizeToSliceKey: "normalizeme", })}, fieldMask: []string{"attributes"}, wantCheckPluginReqFuncs: []checkPluginReqFunc{ - checkUpdateSetRequestCurrentAttributes(map[string]interface{}{ + checkUpdateSetRequestCurrentAttributes(map[string]any{ "foo": "bar", }), - checkUpdateSetRequestNewAttributes(map[string]interface{}{ + checkUpdateSetRequestNewAttributes(map[string]any{ "foo": "baz", normalizeToSliceKey: []any{"normalizeme"}, }), - checkUpdateSetRequestPersistedSecrets(map[string]interface{}{ + checkUpdateSetRequestPersistedSecrets(map[string]any{ "one": "two", }), }, wantCheckSetFuncs: []checkHostSetFunc{ checkVersion(3), - checkAttributes(map[string]interface{}{ + checkAttributes(map[string]any{ "foo": "baz", normalizeToSliceKey: []any{"normalizeme"}, }), @@ -1083,22 +1083,22 @@ func TestRepository_UpdateSet(t *testing.T) { { name: "update attributes (null)", startingSet: setupHostSet, - changeFuncs: []changeHostSetFunc{changeAttributes(map[string]interface{}{ + changeFuncs: []changeHostSetFunc{changeAttributes(map[string]any{ "foo": nil, })}, fieldMask: []string{"attributes"}, wantCheckPluginReqFuncs: []checkPluginReqFunc{ - checkUpdateSetRequestCurrentAttributes(map[string]interface{}{ + checkUpdateSetRequestCurrentAttributes(map[string]any{ "foo": "bar", }), - checkUpdateSetRequestNewAttributes(map[string]interface{}{}), - checkUpdateSetRequestPersistedSecrets(map[string]interface{}{ + checkUpdateSetRequestNewAttributes(map[string]any{}), + checkUpdateSetRequestPersistedSecrets(map[string]any{ "one": "two", }), }, wantCheckSetFuncs: []checkHostSetFunc{ checkVersion(3), - checkAttributes(map[string]interface{}{}), + checkAttributes(map[string]any{}), checkNeedSync(true), checkVerifySetOplog(oplog.OpType_OP_TYPE_UPDATE), }, @@ -1109,17 +1109,17 @@ func TestRepository_UpdateSet(t *testing.T) { changeFuncs: []changeHostSetFunc{changeAttributesNil()}, fieldMask: []string{"attributes"}, wantCheckPluginReqFuncs: []checkPluginReqFunc{ - checkUpdateSetRequestCurrentAttributes(map[string]interface{}{ + checkUpdateSetRequestCurrentAttributes(map[string]any{ "foo": "bar", }), - checkUpdateSetRequestNewAttributes(map[string]interface{}{}), - checkUpdateSetRequestPersistedSecrets(map[string]interface{}{ + checkUpdateSetRequestNewAttributes(map[string]any{}), + checkUpdateSetRequestPersistedSecrets(map[string]any{ "one": "two", }), }, wantCheckSetFuncs: []checkHostSetFunc{ checkVersion(3), - checkAttributes(map[string]interface{}{}), + checkAttributes(map[string]any{}), checkNeedSync(true), checkVerifySetOplog(oplog.OpType_OP_TYPE_UPDATE), }, @@ -1127,26 +1127,26 @@ func TestRepository_UpdateSet(t *testing.T) { { name: "update attributes (combined)", startingSet: setupHostSet, - changeFuncs: []changeHostSetFunc{changeAttributes(map[string]interface{}{ + changeFuncs: []changeHostSetFunc{changeAttributes(map[string]any{ "a": "b", "foo": "baz", })}, fieldMask: []string{"attributes.a", "attributes.foo"}, wantCheckPluginReqFuncs: []checkPluginReqFunc{ - checkUpdateSetRequestCurrentAttributes(map[string]interface{}{ + checkUpdateSetRequestCurrentAttributes(map[string]any{ "foo": "bar", }), - checkUpdateSetRequestNewAttributes(map[string]interface{}{ + checkUpdateSetRequestNewAttributes(map[string]any{ "a": "b", "foo": "baz", }), - checkUpdateSetRequestPersistedSecrets(map[string]interface{}{ + checkUpdateSetRequestPersistedSecrets(map[string]any{ "one": "two", }), }, wantCheckSetFuncs: []checkHostSetFunc{ checkVersion(3), - checkAttributes(map[string]interface{}{ + checkAttributes(map[string]any{ "a": "b", "foo": "baz", }), @@ -1167,7 +1167,7 @@ func TestRepository_UpdateSet(t *testing.T) { checkUpdateSetRequestNewName("foo"), checkUpdateSetRequestCurrentPreferredEndpoints([]string{"cidr:192.168.0.0/24", "cidr:192.168.1.0/24", "cidr:172.16.0.0/12"}), checkUpdateSetRequestNewPreferredEndpoints([]string{"cidr:10.0.0.0/24"}), - checkUpdateSetRequestPersistedSecrets(map[string]interface{}{ + checkUpdateSetRequestPersistedSecrets(map[string]any{ "one": "two", }), }, @@ -1301,7 +1301,7 @@ func TestRepository_UpdateSet(t *testing.T) { for _, check := range []checkPluginReqFunc{ checkUpdateSetRequestCurrentPreferredEndpoints(nil), checkUpdateSetRequestNewPreferredEndpointsNil(), - checkUpdateSetRequestPersistedSecrets(map[string]interface{}{ + checkUpdateSetRequestPersistedSecrets(map[string]any{ "one": "two", }), } { diff --git a/internal/host/plugin/repository_host_util.go b/internal/host/plugin/repository_host_util.go index d272947a0a..0506021860 100644 --- a/internal/host/plugin/repository_host_util.go +++ b/internal/host/plugin/repository_host_util.go @@ -12,16 +12,16 @@ import ( // valueToInterfaceMap is a map that has a function to convert values into an // array -type valueToInterfaceMap map[string]interface{} +type valueToInterfaceMap map[string]any -func (m valueToInterfaceMap) toArray() []interface{} { +func (m valueToInterfaceMap) toArray() []any { switch { case m == nil: return nil case len(m) == 0: - return make([]interface{}, 0) + return make([]any, 0) default: - ret := make([]interface{}, 0, len(m)) + ret := make([]any, 0, len(m)) for _, v := range m { ret = append(ret, v) } diff --git a/internal/host/plugin/repository_host_util_test.go b/internal/host/plugin/repository_host_util_test.go index 9668b6ad3a..7166259003 100644 --- a/internal/host/plugin/repository_host_util_test.go +++ b/internal/host/plugin/repository_host_util_test.go @@ -263,7 +263,7 @@ func TestUtilFunctions(t *testing.T) { hi.ipsToAdd, got.ipsToAdd, cmpopts.IgnoreUnexported(host.IpAddress{}, hoststore.IpAddress{}), - cmpopts.SortSlices(func(x, y interface{}) bool { + cmpopts.SortSlices(func(x, y any) bool { return x.(*host.IpAddress).Address < y.(*host.IpAddress).Address }), ), @@ -273,7 +273,7 @@ func TestUtilFunctions(t *testing.T) { hi.ipsToRemove, got.ipsToRemove, cmpopts.IgnoreUnexported(host.IpAddress{}, hoststore.IpAddress{}), - cmpopts.SortSlices(func(x, y interface{}) bool { + cmpopts.SortSlices(func(x, y any) bool { return x.(*host.IpAddress).Address < y.(*host.IpAddress).Address }), ), @@ -283,7 +283,7 @@ func TestUtilFunctions(t *testing.T) { hi.dnsNamesToAdd, got.dnsNamesToAdd, cmpopts.IgnoreUnexported(host.DnsName{}, hoststore.DnsName{}), - cmpopts.SortSlices(func(x, y interface{}) bool { + cmpopts.SortSlices(func(x, y any) bool { return x.(*host.DnsName).Name < y.(*host.DnsName).Name }), ), @@ -293,7 +293,7 @@ func TestUtilFunctions(t *testing.T) { hi.dnsNamesToRemove, got.dnsNamesToRemove, cmpopts.IgnoreUnexported(host.DnsName{}, hoststore.DnsName{}), - cmpopts.SortSlices(func(x, y interface{}) bool { + cmpopts.SortSlices(func(x, y any) bool { return x.(*host.DnsName).Name < y.(*host.DnsName).Name }), ), diff --git a/internal/host/plugin/testing.go b/internal/host/plugin/testing.go index 022bb00c2a..39ce9cdc84 100644 --- a/internal/host/plugin/testing.go +++ b/internal/host/plugin/testing.go @@ -122,10 +122,10 @@ func TestHost(t testing.TB, conn *db.DB, catId, externId string, opt ...Option) require.NoError(t, err) require.NoError(t, w.Create(ctx, host1)) - var ipAddresses []interface{} + var ipAddresses []any if len(host1.GetIpAddresses()) > 0 { sort.Strings(host1.IpAddresses) - ipAddresses = make([]interface{}, 0, len(host1.GetIpAddresses())) + ipAddresses = make([]any, 0, len(host1.GetIpAddresses())) for _, a := range host1.GetIpAddresses() { obj, err := host.NewIpAddress(ctx, host1.PublicId, a) require.NoError(t, err) @@ -134,10 +134,10 @@ func TestHost(t testing.TB, conn *db.DB, catId, externId string, opt ...Option) require.NoError(t, w.CreateItems(ctx, ipAddresses)) } - var dnsNames []interface{} + var dnsNames []any if len(host1.GetDnsNames()) > 0 { sort.Strings(host1.DnsNames) - dnsNames = make([]interface{}, 0, len(host1.GetDnsNames())) + dnsNames = make([]any, 0, len(host1.GetDnsNames())) for _, n := range host1.GetDnsNames() { obj, err := host.NewDnsName(ctx, host1.PublicId, n) require.NoError(t, err) diff --git a/internal/host/preferred_endpoint_test.go b/internal/host/preferred_endpoint_test.go index dc784a6508..cdff77ab69 100644 --- a/internal/host/preferred_endpoint_test.go +++ b/internal/host/preferred_endpoint_test.go @@ -141,7 +141,7 @@ func TestPreferredEndpoint_Create(t *testing.T) { assert.NoError(err) } found := host.AllocPreferredEndpoint() - require.NoError(rw.LookupWhere(ctx, found, "host_set_id = ? and priority = ?", []interface{}{tt.args.hostSetId, tt.args.priority})) + require.NoError(rw.LookupWhere(ctx, found, "host_set_id = ? and priority = ?", []any{tt.args.hostSetId, tt.args.priority})) assert.Equal(got, found) } }) @@ -220,7 +220,7 @@ func TestPreferredEndpoint_Delete(t *testing.T) { } require.Equal(tt.wantRowsDeleted, deletedRows) found := host.AllocPreferredEndpoint() - err = rw.LookupWhere(ctx, &found, "host_set_id = ?", []interface{}{set.PublicId}) + err = rw.LookupWhere(ctx, &found, "host_set_id = ?", []any{set.PublicId}) assert.True(errors.IsNotFoundError(err)) }) } diff --git a/internal/host/static/immutable_fields_test.go b/internal/host/static/immutable_fields_test.go index 9196ab26af..9b92332696 100644 --- a/internal/host/static/immutable_fields_test.go +++ b/internal/host/static/immutable_fields_test.go @@ -270,7 +270,7 @@ func TestStaticHostSetMember_ImmutableFields(t *testing.T) { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) orig := new.testCloneHostSetMember() - err = w.LookupWhere(context.Background(), orig, "host_id = ? and set_id = ?", []interface{}{orig.HostId, orig.SetId}) + err = w.LookupWhere(context.Background(), orig, "host_id = ? and set_id = ?", []any{orig.HostId, orig.SetId}) require.NoError(err) rowsUpdated, err := w.Update(context.Background(), tt.update, tt.fieldMask, nil, db.WithSkipVetForWrite(true)) @@ -278,7 +278,7 @@ func TestStaticHostSetMember_ImmutableFields(t *testing.T) { assert.Equal(0, rowsUpdated) after := new.testCloneHostSetMember() - err = w.LookupWhere(context.Background(), after, "host_id = ? and set_id = ?", []interface{}{after.HostId, after.SetId}) + err = w.LookupWhere(context.Background(), after, "host_id = ? and set_id = ?", []any{after.HostId, after.SetId}) require.NoError(err) assert.True(proto.Equal(orig, after)) diff --git a/internal/host/static/repository_host.go b/internal/host/static/repository_host.go index 174ed17aaa..9e964eea88 100644 --- a/internal/host/static/repository_host.go +++ b/internal/host/static/repository_host.go @@ -142,7 +142,7 @@ func (r *Repository) UpdateHost(ctx context.Context, projectId string, h *Host, } var dbMask, nullFields []string dbMask, nullFields = dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ "Name": h.Name, "Description": h.Description, "Address": h.Address, @@ -236,7 +236,7 @@ func (r *Repository) ListHosts(ctx context.Context, catalogId string, opt ...Opt limit = opts.withLimit } var aggs []*hostAgg - err := r.reader.SearchWhere(ctx, &aggs, "catalog_id = ?", []interface{}{catalogId}, db.WithLimit(limit)) + err := r.reader.SearchWhere(ctx, &aggs, "catalog_id = ?", []any{catalogId}, db.WithLimit(limit)) if err != nil { return nil, errors.Wrap(ctx, err, op) } diff --git a/internal/host/static/repository_host_catalog.go b/internal/host/static/repository_host_catalog.go index 621eb54634..e16cf221a6 100644 --- a/internal/host/static/repository_host_catalog.go +++ b/internal/host/static/repository_host_catalog.go @@ -213,7 +213,7 @@ func (r *Repository) ListCatalogs(ctx context.Context, projectIds []string, opt limit = opts.withLimit } var hostCatalogs []*HostCatalog - err := r.reader.SearchWhere(ctx, &hostCatalogs, "project_id in (?)", []interface{}{projectIds}, db.WithLimit(limit)) + err := r.reader.SearchWhere(ctx, &hostCatalogs, "project_id in (?)", []any{projectIds}, db.WithLimit(limit)) if err != nil { return nil, errors.Wrap(ctx, err, op) } diff --git a/internal/host/static/repository_host_set.go b/internal/host/static/repository_host_set.go index ff2c0d99df..b1136dcc90 100644 --- a/internal/host/static/repository_host_set.go +++ b/internal/host/static/repository_host_set.go @@ -126,7 +126,7 @@ func (r *Repository) UpdateSet(ctx context.Context, projectId string, s *HostSet } var dbMask, nullFields []string dbMask, nullFields = dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ "Name": s.Name, "Description": s.Description, }, @@ -258,7 +258,7 @@ func (r *Repository) ListSets(ctx context.Context, catalogId string, opt ...Opti limit = opts.withLimit } var sets []*HostSet - err := r.reader.SearchWhere(ctx, &sets, "catalog_id = ?", []interface{}{catalogId}, db.WithLimit(limit)) + err := r.reader.SearchWhere(ctx, &sets, "catalog_id = ?", []any{catalogId}, db.WithLimit(limit)) if err != nil { return nil, errors.Wrap(ctx, err, op) } diff --git a/internal/host/static/repository_host_set_member.go b/internal/host/static/repository_host_set_member.go index f2fc91f03c..8f7f9700a3 100644 --- a/internal/host/static/repository_host_set_member.go +++ b/internal/host/static/repository_host_set_member.go @@ -71,8 +71,8 @@ func (r *Repository) AddSetMembers(ctx context.Context, projectId string, setId return hosts, nil } -func (r *Repository) newMembers(ctx context.Context, setId string, hostIds []string) ([]interface{}, error) { - var members []interface{} +func (r *Repository) newMembers(ctx context.Context, setId string, hostIds []string) ([]any, error) { + var members []any for _, id := range hostIds { var m *HostSetMember m, err := NewHostSetMember(setId, id) @@ -84,7 +84,7 @@ func (r *Repository) newMembers(ctx context.Context, setId string, hostIds []str return members, nil } -func createMembers(ctx context.Context, w db.Writer, members []interface{}) ([]*oplog.Message, error) { +func createMembers(ctx context.Context, w db.Writer, members []any) ([]*oplog.Message, error) { var msgs []*oplog.Message if err := w.CreateItems(ctx, members, db.NewOplogMsgs(&msgs)); err != nil { return nil, errors.Wrap(ctx, err, "static.createMembers") @@ -134,7 +134,7 @@ func getHosts(ctx context.Context, reader db.Reader, setId string, limit int) ([ limit ? )` - params := []interface{}{setId} + params := []any{setId} var where string switch limit { case unlimited: @@ -211,7 +211,7 @@ func (r *Repository) DeleteSetMembers(ctx context.Context, projectId string, set return len(hostIds), nil } -func deleteMembers(ctx context.Context, w db.Writer, members []interface{}) ([]*oplog.Message, error) { +func deleteMembers(ctx context.Context, w db.Writer, members []any) ([]*oplog.Message, error) { const op = "static.deleteMembers" var msgs []*oplog.Message rowsDeleted, err := w.DeleteItems(ctx, members, db.NewOplogMsgs(&msgs)) @@ -258,7 +258,7 @@ func (r *Repository) SetSetMembers(ctx context.Context, projectId string, setId if err != nil { return nil, db.NoRowsAffected, errors.Wrap(ctx, err, op) } - var deletions, additions []interface{} + var deletions, additions []any for _, c := range changes { m, err := NewHostSetMember(setId, c.HostId) if err != nil { @@ -341,7 +341,7 @@ func (r *Repository) changes(ctx context.Context, setId string, hostIds []string } query := fmt.Sprintf(setChangesQuery, inClause) - var params []interface{} + var params []any params = append(params, sql.Named("1", setId)) for idx, v := range hostIds { params = append(params, sql.Named(fmt.Sprintf("%d", idx+2), v)) diff --git a/internal/iam/account.go b/internal/iam/account.go index 8a902e07b1..593cffabfc 100644 --- a/internal/iam/account.go +++ b/internal/iam/account.go @@ -35,7 +35,7 @@ func allocAccount() authAccount { } // Clone creates a clone of the auth account. -func (a *authAccount) Clone() interface{} { +func (a *authAccount) Clone() any { cp := proto.Clone(a.Account) return &authAccount{ Account: cp.(*authStore.Account), diff --git a/internal/iam/group.go b/internal/iam/group.go index ae514e2328..2fea382b9e 100644 --- a/internal/iam/group.go +++ b/internal/iam/group.go @@ -48,7 +48,7 @@ func NewGroup(scopeId string, opt ...Option) (*Group, error) { } // Clone creates a clone of the Group. -func (g *Group) Clone() interface{} { +func (g *Group) Clone() any { cp := proto.Clone(g.Group) return &Group{ Group: cp.(*store.Group), diff --git a/internal/iam/group_member.go b/internal/iam/group_member.go index 2f871970e2..2ae051441b 100644 --- a/internal/iam/group_member.go +++ b/internal/iam/group_member.go @@ -93,7 +93,7 @@ func allocGroupMember() GroupMemberUser { } // Clone creates a clone of the GroupMember -func (m *GroupMemberUser) Clone() interface{} { +func (m *GroupMemberUser) Clone() any { cp := proto.Clone(m.GroupMemberUser) return &GroupMemberUser{ GroupMemberUser: cp.(*store.GroupMemberUser), diff --git a/internal/iam/group_member_test.go b/internal/iam/group_member_test.go index cf49039d06..c66b9b3d48 100644 --- a/internal/iam/group_member_test.go +++ b/internal/iam/group_member_test.go @@ -253,7 +253,7 @@ func Test_GroupMemberCreate(t *testing.T) { assert.NoError(err) found := allocGroupMember() - err = w.LookupWhere(context.Background(), &found, "group_id = ? and member_id = ?", []interface{}{gm.GroupId, gm.MemberId}) + err = w.LookupWhere(context.Background(), &found, "group_id = ? and member_id = ?", []any{gm.GroupId, gm.MemberId}) require.NoError(err) assert.Empty(cmp.Diff(gm, &found, protocmp.Transform())) }) @@ -331,7 +331,7 @@ func Test_GroupMemberDelete(t *testing.T) { } assert.Equal(tt.wantRowsDeleted, deletedRows) found := allocGroupMember() - err = rw.LookupWhere(context.Background(), &found, "group_id = ? and member_id = ?", []interface{}{tt.gm.GetGroupId(), tt.gm.GetMemberId()}) + err = rw.LookupWhere(context.Background(), &found, "group_id = ? and member_id = ?", []any{tt.gm.GetGroupId(), tt.gm.GetMemberId()}) require.Error(err) assert.True(errors.IsNotFoundError(err)) }) diff --git a/internal/iam/principal_role.go b/internal/iam/principal_role.go index 0c7bfb4dd3..ab85f29952 100644 --- a/internal/iam/principal_role.go +++ b/internal/iam/principal_role.go @@ -100,7 +100,7 @@ func allocUserRole() UserRole { } // Clone creates a clone of the UserRole. -func (r *UserRole) Clone() interface{} { +func (r *UserRole) Clone() any { cp := proto.Clone(r.UserRole) return &UserRole{ UserRole: cp.(*store.UserRole), @@ -177,7 +177,7 @@ func allocGroupRole() GroupRole { } // Clone creates a clone of the GroupRole. -func (r *GroupRole) Clone() interface{} { +func (r *GroupRole) Clone() any { cp := proto.Clone(r.GroupRole) return &GroupRole{ GroupRole: cp.(*store.GroupRole), @@ -256,7 +256,7 @@ func AllocManagedGroupRole() ManagedGroupRole { } // Clone creates a clone of the ManagedGroupRole. -func (r *ManagedGroupRole) Clone() interface{} { +func (r *ManagedGroupRole) Clone() any { cp := proto.Clone(r.ManagedGroupRole) return &ManagedGroupRole{ ManagedGroupRole: cp.(*store.ManagedGroupRole), diff --git a/internal/iam/principal_role_ext_test.go b/internal/iam/principal_role_ext_test.go index 38c794d0d3..c30b456110 100644 --- a/internal/iam/principal_role_ext_test.go +++ b/internal/iam/principal_role_ext_test.go @@ -246,7 +246,7 @@ func TestManagedGroupRole_Create(t *testing.T) { assert.NoError(err) found := iam.AllocManagedGroupRole() - err = w.LookupWhere(context.Background(), &found, "role_id = ? and principal_id = ?", []interface{}{r.RoleId, r.PrincipalId}) + err = w.LookupWhere(context.Background(), &found, "role_id = ? and principal_id = ?", []any{r.RoleId, r.PrincipalId}) require.NoError(err) assert.Empty(cmp.Diff(r, &found, protocmp.Transform())) }) @@ -360,7 +360,7 @@ func TestManagedGroupRole_Delete(t *testing.T) { } assert.Equal(tt.wantRowsDeleted, deletedRows) found := iam.AllocManagedGroupRole() - err = rw.LookupWhere(context.Background(), &found, "role_id = ? and principal_id = ?", []interface{}{tt.role.GetRoleId(), tt.role.GetPrincipalId()}) + err = rw.LookupWhere(context.Background(), &found, "role_id = ? and principal_id = ?", []any{tt.role.GetRoleId(), tt.role.GetPrincipalId()}) require.Error(err) assert.True(errors.IsNotFoundError(err)) }) diff --git a/internal/iam/principal_role_test.go b/internal/iam/principal_role_test.go index d46ab3dc26..1cc8d3053a 100644 --- a/internal/iam/principal_role_test.go +++ b/internal/iam/principal_role_test.go @@ -265,7 +265,7 @@ func TestUserRole_Create(t *testing.T) { assert.NoError(err) found := allocUserRole() - err = w.LookupWhere(context.Background(), &found, "role_id = ? and principal_id = ?", []interface{}{r.RoleId, r.PrincipalId}) + err = w.LookupWhere(context.Background(), &found, "role_id = ? and principal_id = ?", []any{r.RoleId, r.PrincipalId}) require.NoError(err) assert.Empty(cmp.Diff(r, &found, protocmp.Transform())) }) @@ -343,7 +343,7 @@ func TestUserRole_Delete(t *testing.T) { } assert.Equal(tt.wantRowsDeleted, deletedRows) found := allocUserRole() - err = rw.LookupWhere(context.Background(), &found, "role_id = ? and principal_id = ?", []interface{}{tt.role.GetRoleId(), tt.role.GetPrincipalId()}) + err = rw.LookupWhere(context.Background(), &found, "role_id = ? and principal_id = ?", []any{tt.role.GetRoleId(), tt.role.GetPrincipalId()}) require.Error(err) assert.True(errors.IsNotFoundError(err)) }) @@ -641,7 +641,7 @@ func TestGroupRole_Create(t *testing.T) { assert.NoError(err) found := allocGroupRole() - err = w.LookupWhere(context.Background(), &found, "role_id = ? and principal_id = ?", []interface{}{r.RoleId, r.PrincipalId}) + err = w.LookupWhere(context.Background(), &found, "role_id = ? and principal_id = ?", []any{r.RoleId, r.PrincipalId}) require.NoError(err) assert.Empty(cmp.Diff(r, &found, protocmp.Transform())) }) @@ -724,7 +724,7 @@ func TestGroupRole_Delete(t *testing.T) { } assert.Equal(tt.wantRowsDeleted, deletedRows) found := allocGroupRole() - err = rw.LookupWhere(context.Background(), &found, "role_id = ? and principal_id = ?", []interface{}{tt.role.GetRoleId(), tt.role.GetPrincipalId()}) + err = rw.LookupWhere(context.Background(), &found, "role_id = ? and principal_id = ?", []any{tt.role.GetRoleId(), tt.role.GetPrincipalId()}) require.Error(err) assert.True(errors.IsNotFoundError(err)) }) diff --git a/internal/iam/repository.go b/internal/iam/repository.go index 17cf4db871..b833bb970e 100644 --- a/internal/iam/repository.go +++ b/internal/iam/repository.go @@ -52,7 +52,7 @@ func NewRepository(r db.Reader, w db.Writer, kms *kms.Kms, opt ...Option) (*Repo // list will return a listing of resources and honor the WithLimit option or the // repo defaultLimit -func (r *Repository) list(ctx context.Context, resources interface{}, where string, args []interface{}, opt ...Option) error { +func (r *Repository) list(ctx context.Context, resources any, where string, args []any, opt ...Option) error { opts := getOpts(opt...) limit := r.defaultLimit if opts.withLimit != 0 { @@ -87,7 +87,7 @@ func (r *Repository) create(ctx context.Context, resource Resource, _ ...Option) return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper")) } - var returnedResource interface{} + var returnedResource any _, err = r.writer.DoTx( ctx, db.StdRetryCnt, @@ -155,7 +155,7 @@ func (r *Repository) update(ctx context.Context, resource Resource, version uint dbOpts = append(dbOpts, db.WithOplog(oplogWrapper, metadata)) var rowsUpdated int - var returnedResource interface{} + var returnedResource any _, err = r.writer.DoTx( ctx, db.StdRetryCnt, @@ -211,7 +211,7 @@ func (r *Repository) delete(ctx context.Context, resource Resource, _ ...Option) } var rowsDeleted int - var deleteResource interface{} + var deleteResource any _, err = r.writer.DoTx( ctx, db.StdRetryCnt, diff --git a/internal/iam/repository_group.go b/internal/iam/repository_group.go index 437ede0cea..2ba0cc3ce3 100644 --- a/internal/iam/repository_group.go +++ b/internal/iam/repository_group.go @@ -70,7 +70,7 @@ func (r *Repository) UpdateGroup(ctx context.Context, group *Group, version uint } var dbMask, nullFields []string dbMask, nullFields = dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ "name": group.Name, "description": group.Description, }, @@ -177,7 +177,7 @@ func (r *Repository) ListGroups(ctx context.Context, withScopeIds []string, opt return nil, errors.New(ctx, errors.InvalidParameter, op, "missing scope id") } var grps []*Group - err := r.list(ctx, &grps, "scope_id in (?)", []interface{}{withScopeIds}, opt...) + err := r.list(ctx, &grps, "scope_id in (?)", []any{withScopeIds}, opt...) if err != nil { return nil, errors.Wrap(ctx, err, op) } @@ -191,7 +191,7 @@ func (r *Repository) ListGroupMembers(ctx context.Context, withGroupId string, o return nil, errors.New(ctx, errors.InvalidParameter, op, "missing group id") } members := []*GroupMember{} - if err := r.list(ctx, &members, "group_id = ?", []interface{}{withGroupId}, opt...); err != nil { + if err := r.list(ctx, &members, "group_id = ?", []any{withGroupId}, opt...); err != nil { return nil, errors.Wrap(ctx, err, op) } return members, nil @@ -219,7 +219,7 @@ func (r *Repository) AddGroupMembers(ctx context.Context, groupId string, groupV return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to get group members %s scope", groupId))) } - newGroupMembers := make([]interface{}, 0, len(userIds)) + newGroupMembers := make([]any, 0, len(userIds)) for _, id := range userIds { gm, err := NewGroupMemberUser(groupId, id) if err != nil { @@ -312,7 +312,7 @@ func (r *Repository) DeleteGroupMembers(ctx context.Context, groupId string, gro return db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to get group members %s scope", groupId))) } - deleteMembers := make([]interface{}, 0, len(userIds)) + deleteMembers := make([]any, 0, len(userIds)) for _, id := range userIds { member, err := NewGroupMemberUser(groupId, id) if err != nil { @@ -494,7 +494,7 @@ func (r *Repository) SetGroupMembers(ctx context.Context, groupId string, groupV } // groupMemberChanges returns two slices: members to add and delete -func groupMemberChanges(ctx context.Context, reader db.Reader, groupId string, userIds []string) ([]interface{}, []interface{}, error) { +func groupMemberChanges(ctx context.Context, reader db.Reader, groupId string, userIds []string) ([]any, []any, error) { const op = "iam.groupMemberChanges" var inClauseSpots []string // starts at 2 because there is already a ? in the query @@ -507,7 +507,7 @@ func groupMemberChanges(ctx context.Context, reader db.Reader, groupId string, u } query := fmt.Sprintf(grpMemberChangesQuery, inClause) - var params []interface{} + var params []any for _, v := range userIds { params = append(params, v) } @@ -531,8 +531,8 @@ func groupMemberChanges(ctx context.Context, reader db.Reader, groupId string, u } changes = append(changes, &chg) } - addMembers := []interface{}{} - deleteMembers := []interface{}{} + addMembers := []any{} + deleteMembers := []any{} for _, c := range changes { if c.MemberId == "" { return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing user id in change result") diff --git a/internal/iam/repository_group_test.go b/internal/iam/repository_group_test.go index dfa24846e3..4df0c67faa 100644 --- a/internal/iam/repository_group_test.go +++ b/internal/iam/repository_group_test.go @@ -421,7 +421,7 @@ func TestRepository_UpdateGroup(t *testing.T) { var err error if tt.directUpdate { g := updateGrp.Clone() - var resource interface{} + var resource any resource, updatedRows, err = repo.update(context.Background(), g.(*Group), updateGrp.Version, tt.args.fieldMaskPaths, nil, tt.args.opt...) if err == nil { groupAfterUpdate = resource.(*Group) @@ -627,7 +627,7 @@ func TestRepository_ListGroups(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { i := allocGroup(); ; return &i }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { i := allocGroup(); ; return &i }(), "1=1") testGroups := []*Group{} for i := 0; i < tt.createCnt; i++ { testGroups = append(testGroups, TestGroup(t, conn, tt.createScopeId)) @@ -651,7 +651,7 @@ func TestRepository_ListGroups_Multiple_Scopes(t *testing.T) { repo := TestRepo(t, conn, wrapper) org, proj := TestScopes(t, repo) - db.TestDeleteWhere(t, conn, func() interface{} { g := allocGroup(); return &g }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { g := allocGroup(); return &g }(), "1=1") const numPerScope = 10 var total int @@ -733,7 +733,7 @@ func TestRepository_ListMembers(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { i := allocGroupMember(); ; return &i }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { i := allocGroupMember(); ; return &i }(), "1=1") gm := []*GroupMemberUser{} for i := 0; i < tt.createCnt; i++ { u := TestUser(t, repo, org.PublicId) diff --git a/internal/iam/repository_principal_role.go b/internal/iam/repository_principal_role.go index 87f24ddc61..da2e6941b7 100644 --- a/internal/iam/repository_principal_role.go +++ b/internal/iam/repository_principal_role.go @@ -33,7 +33,7 @@ func (r *Repository) AddPrincipalRoles(ctx context.Context, roleId string, roleV return nil, errors.New(ctx, errors.InvalidParameter, op, "missing any of users, groups, or managed groups to add") } - newUserRoles := make([]interface{}, 0, len(userIds)) + newUserRoles := make([]any, 0, len(userIds)) for _, id := range userIds { usrRole, err := NewUserRole(roleId, id) if err != nil { @@ -41,7 +41,7 @@ func (r *Repository) AddPrincipalRoles(ctx context.Context, roleId string, roleV } newUserRoles = append(newUserRoles, usrRole) } - newGrpRoles := make([]interface{}, 0, len(groupIds)) + newGrpRoles := make([]any, 0, len(groupIds)) for _, id := range groupIds { grpRole, err := NewGroupRole(roleId, id) if err != nil { @@ -49,7 +49,7 @@ func (r *Repository) AddPrincipalRoles(ctx context.Context, roleId string, roleV } newGrpRoles = append(newGrpRoles, grpRole) } - newManagedGrpRoles := make([]interface{}, 0, len(managedGroupIds)) + newManagedGrpRoles := make([]any, 0, len(managedGroupIds)) for _, id := range managedGroupIds { managedGrpRole, err := NewManagedGroupRole(roleId, id) if err != nil { @@ -335,7 +335,7 @@ func (r *Repository) DeletePrincipalRoles(ctx context.Context, roleId string, ro role := allocRole() role.PublicId = roleId - deleteUserRoles := make([]interface{}, 0, len(userIds)) + deleteUserRoles := make([]any, 0, len(userIds)) for _, id := range userIds { usrRole, err := NewUserRole(roleId, id) if err != nil { @@ -343,7 +343,7 @@ func (r *Repository) DeletePrincipalRoles(ctx context.Context, roleId string, ro } deleteUserRoles = append(deleteUserRoles, usrRole) } - deleteGrpRoles := make([]interface{}, 0, len(groupIds)) + deleteGrpRoles := make([]any, 0, len(groupIds)) for _, id := range groupIds { grpRole, err := NewGroupRole(roleId, id) if err != nil { @@ -351,7 +351,7 @@ func (r *Repository) DeletePrincipalRoles(ctx context.Context, roleId string, ro } deleteGrpRoles = append(deleteGrpRoles, grpRole) } - deleteManagedGrpRoles := make([]interface{}, 0, len(managedGroupIds)) + deleteManagedGrpRoles := make([]any, 0, len(managedGroupIds)) for _, id := range managedGroupIds { managedGrpRole, err := NewManagedGroupRole(roleId, id) if err != nil { @@ -453,7 +453,7 @@ func (r *Repository) ListPrincipalRoles(ctx context.Context, roleId string, opt return nil, errors.New(ctx, errors.InvalidParameter, op, "missing role id") } var roles []*PrincipalRole - if err := r.list(ctx, &roles, "role_id = ?", []interface{}{roleId}, opt...); err != nil { + if err := r.list(ctx, &roles, "role_id = ?", []any{roleId}, opt...); err != nil { return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to lookup roles")) } principals := make([]*PrincipalRole, 0, len(roles)) @@ -462,12 +462,12 @@ func (r *Repository) ListPrincipalRoles(ctx context.Context, roleId string, opt } type PrincipalSet struct { - AddUserRoles []interface{} - AddGroupRoles []interface{} - AddManagedGroupRoles []interface{} - DeleteUserRoles []interface{} - DeleteGroupRoles []interface{} - DeleteManagedGroupRoles []interface{} + AddUserRoles []any + AddGroupRoles []any + AddManagedGroupRoles []any + DeleteUserRoles []any + DeleteGroupRoles []any + DeleteManagedGroupRoles []any // unchangedPrincipalRoles is set iff there are no changes, that is, the // length of all other members is zero UnchangedPrincipalRoles []*PrincipalRole @@ -500,7 +500,7 @@ func (r *Repository) PrincipalsToSet(ctx context.Context, role *Role, userIds, g return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("%s is unknown principal type %s", p.PrincipalId, p.GetType())) } } - var newUserRoles []interface{} + var newUserRoles []any userIdsMap := map[string]struct{}{} for _, id := range userIds { userIdsMap[id] = struct{}{} @@ -512,7 +512,7 @@ func (r *Repository) PrincipalsToSet(ctx context.Context, role *Role, userIds, g newUserRoles = append(newUserRoles, usrRole) } } - var newGrpRoles []interface{} + var newGrpRoles []any groupIdsMap := map[string]struct{}{} for _, id := range groupIds { groupIdsMap[id] = struct{}{} @@ -524,7 +524,7 @@ func (r *Repository) PrincipalsToSet(ctx context.Context, role *Role, userIds, g newGrpRoles = append(newGrpRoles, grpRole) } } - var newManagedGrpRoles []interface{} + var newManagedGrpRoles []any managedGroupIdsMap := map[string]struct{}{} for _, id := range managedGroupIds { managedGroupIdsMap[id] = struct{}{} @@ -536,7 +536,7 @@ func (r *Repository) PrincipalsToSet(ctx context.Context, role *Role, userIds, g newManagedGrpRoles = append(newManagedGrpRoles, managedGrpRole) } } - var deleteUserRoles []interface{} + var deleteUserRoles []any for _, p := range existingUsers { if _, ok := userIdsMap[p.PrincipalId]; !ok { usrRole, err := NewUserRole(p.GetRoleId(), p.GetPrincipalId()) @@ -546,7 +546,7 @@ func (r *Repository) PrincipalsToSet(ctx context.Context, role *Role, userIds, g deleteUserRoles = append(deleteUserRoles, usrRole) } } - var deleteGrpRoles []interface{} + var deleteGrpRoles []any for _, p := range existingGroups { if _, ok := groupIdsMap[p.PrincipalId]; !ok { grpRole, err := NewGroupRole(p.GetRoleId(), p.GetPrincipalId()) @@ -556,7 +556,7 @@ func (r *Repository) PrincipalsToSet(ctx context.Context, role *Role, userIds, g deleteGrpRoles = append(deleteGrpRoles, grpRole) } } - var deleteManagedGrpRoles []interface{} + var deleteManagedGrpRoles []any for _, p := range existingManagedGroups { if _, ok := managedGroupIdsMap[p.PrincipalId]; !ok { managedGrpRole, err := NewManagedGroupRole(p.GetRoleId(), p.GetPrincipalId()) diff --git a/internal/iam/repository_principal_role_test.go b/internal/iam/repository_principal_role_test.go index 16c5edb0af..fd170fe137 100644 --- a/internal/iam/repository_principal_role_test.go +++ b/internal/iam/repository_principal_role_test.go @@ -125,8 +125,8 @@ func TestRepository_AddPrincipalRoles(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { r := allocUserRole(); return &r }(), "1=1") - db.TestDeleteWhere(t, conn, func() interface{} { g := allocGroupRole(); return &g }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { r := allocUserRole(); return &r }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { g := allocGroupRole(); return &g }(), "1=1") orgs, projects := createScopesFn() var userIds, groupIds []string @@ -264,7 +264,7 @@ func TestRepository_ListPrincipalRoles(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { r := allocRole(); return &r }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { r := allocRole(); return &r }(), "1=1") role := TestRole(t, conn, tt.createScopeId) userRoles := make([]string, 0, tt.createCnt) groupRoles := make([]string, 0, tt.createCnt) diff --git a/internal/iam/repository_role.go b/internal/iam/repository_role.go index 5b17675c79..f56abdd6c6 100644 --- a/internal/iam/repository_role.go +++ b/internal/iam/repository_role.go @@ -70,7 +70,7 @@ func (r *Repository) UpdateRole(ctx context.Context, role *Role, version uint32, } var dbMask, nullFields []string dbMask, nullFields = dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ "name": role.Name, "description": role.Description, "GrantScopeId": role.GrantScopeId, @@ -188,7 +188,7 @@ func (r *Repository) ListRoles(ctx context.Context, withScopeIds []string, opt . return nil, errors.New(ctx, errors.InvalidParameter, op, "missing scope ids") } var roles []*Role - err := r.list(ctx, &roles, "scope_id in (?)", []interface{}{withScopeIds}, opt...) + err := r.list(ctx, &roles, "scope_id in (?)", []any{withScopeIds}, opt...) if err != nil { return nil, errors.Wrap(ctx, err, op) } diff --git a/internal/iam/repository_role_grant.go b/internal/iam/repository_role_grant.go index 4453334140..d649a4ca21 100644 --- a/internal/iam/repository_role_grant.go +++ b/internal/iam/repository_role_grant.go @@ -28,7 +28,7 @@ func (r *Repository) AddRoleGrants(ctx context.Context, roleId string, roleVersi role := allocRole() role.PublicId = roleId - newRoleGrants := make([]interface{}, 0, len(grants)) + newRoleGrants := make([]any, 0, len(grants)) for _, grant := range grants { roleGrant, err := NewRoleGrant(roleId, grant) if err != nil { @@ -152,7 +152,7 @@ func (r *Repository) DeleteRoleGrants(ctx context.Context, roleId string, roleVe // Find existing grants roleGrants := []*RoleGrant{} - if err := reader.SearchWhere(ctx, &roleGrants, "role_id = ?", []interface{}{roleId}); err != nil { + if err := reader.SearchWhere(ctx, &roleGrants, "role_id = ?", []any{roleId}); err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg("unable to search for grants")) } found := map[string]bool{} @@ -162,7 +162,7 @@ func (r *Repository) DeleteRoleGrants(ctx context.Context, roleId string, roleVe // Check incoming grants to see if they exist and if so add to // delete slice - deleteRoleGrants := make([]interface{}, 0, len(grants)) + deleteRoleGrants := make([]any, 0, len(grants)) for _, grant := range grants { // Use a fake scope, just want to get out a canonical string perm, err := perms.Parse("o_abcd1234", grant, perms.WithSkipFinalValidation(true)) @@ -243,7 +243,7 @@ func (r *Repository) SetRoleGrants(ctx context.Context, roleId string, roleVersi // Find existing grants roleGrants := []*RoleGrant{} - if err := r.reader.SearchWhere(ctx, &roleGrants, "role_id = ?", []interface{}{roleId}); err != nil { + if err := r.reader.SearchWhere(ctx, &roleGrants, "role_id = ?", []any{roleId}); err != nil { return nil, db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("unable to search for grants")) } found := map[string]*RoleGrant{} @@ -253,8 +253,8 @@ func (r *Repository) SetRoleGrants(ctx context.Context, roleId string, roleVersi // Check incoming grants to see if they exist and if so act appropriately currentRoleGrants := make([]*RoleGrant, 0, len(grants)+len(found)) - addRoleGrants := make([]interface{}, 0, len(grants)) - deleteRoleGrants := make([]interface{}, 0, len(grants)) + addRoleGrants := make([]any, 0, len(grants)) + deleteRoleGrants := make([]any, 0, len(grants)) for _, grant := range grants { // Use a fake scope, just want to get out a canonical string perm, err := perms.Parse("o_abcd1234", grant, perms.WithSkipFinalValidation(true)) @@ -379,7 +379,7 @@ func (r *Repository) ListRoleGrants(ctx context.Context, roleId string, opt ...O return nil, errors.New(ctx, errors.InvalidParameter, op, "missing role id") } var roleGrants []*RoleGrant - if err := r.list(ctx, &roleGrants, "role_id = ?", []interface{}{roleId}, opt...); err != nil { + if err := r.list(ctx, &roleGrants, "role_id = ?", []any{roleId}, opt...); err != nil { return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to lookup role grants")) } return roleGrants, nil @@ -476,7 +476,7 @@ select role_id as role_id, role_scope as scope_id, role_grant as grant from fina } var grants []perms.GrantTuple - rows, err := r.reader.Query(ctx, query, []interface{}{userId}) + rows, err := r.reader.Query(ctx, query, []any{userId}) if err != nil { return nil, errors.Wrap(ctx, err, op) } diff --git a/internal/iam/repository_role_grant_test.go b/internal/iam/repository_role_grant_test.go index 6aeabdd980..8f63f57add 100644 --- a/internal/iam/repository_role_grant_test.go +++ b/internal/iam/repository_role_grant_test.go @@ -82,7 +82,7 @@ func TestRepository_AddRoleGrants(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { rg := allocRoleGrant(); return &rg }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { rg := allocRoleGrant(); return &rg }(), "1=1") got, err := repo.AddRoleGrants(context.Background(), tt.args.roleId, tt.args.roleVersion, tt.args.grants, tt.args.opt...) if tt.wantErr { require.Error(err) @@ -190,7 +190,7 @@ func TestRepository_ListRoleGrants(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { r := allocRole(); return &r }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { r := allocRole(); return &r }(), "1=1") role := TestRole(t, conn, tt.createScopeId) roleGrants := make([]string, 0, tt.createCnt) for i := 0; i < tt.createCnt; i++ { @@ -333,7 +333,7 @@ func TestRepository_DeleteRoleGrants(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { rg := allocRoleGrant(); return &rg }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { rg := allocRoleGrant(); return &rg }(), "1=1") grants := make([]*RoleGrant, 0, tt.args.createCnt) grantStrings := make([]string, 0, tt.args.createCnt) for i := 0; i < tt.args.createCnt; i++ { @@ -385,7 +385,7 @@ func TestRepository_DeleteRoleGrants(t *testing.T) { assert.Equal(tt.wantRowsDeleted, deletedRows) roleGrants = []*RoleGrant{} - require.NoError(repo.reader.SearchWhere(context.Background(), &roleGrants, "role_id = ?", []interface{}{roleId})) + require.NoError(repo.reader.SearchWhere(context.Background(), &roleGrants, "role_id = ?", []any{roleId})) found := map[string]bool{} for _, rg := range roleGrants { found[rg.CanonicalGrant] = true @@ -408,7 +408,7 @@ func TestRepository_SetRoleGrants_Randomize(t *testing.T) { repo := TestRepo(t, conn, wrapper) org, _ := TestScopes(t, repo) role := TestRole(t, conn, org.PublicId) - db.TestDeleteWhere(t, conn, func() interface{} { i := allocRoleGrant(); return &i }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { i := allocRoleGrant(); return &i }(), "1=1") type roleGrantWrapper struct { grantString string diff --git a/internal/iam/repository_role_test.go b/internal/iam/repository_role_test.go index 3635f55518..face2b9738 100644 --- a/internal/iam/repository_role_test.go +++ b/internal/iam/repository_role_test.go @@ -625,7 +625,7 @@ func TestRepository_ListRoles(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { r := allocRole(); return &r }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { r := allocRole(); return &r }(), "1=1") testRoles := []*Role{} for i := 0; i < tt.createCnt; i++ { testRoles = append(testRoles, TestRole(t, conn, tt.createScopeId)) @@ -649,7 +649,7 @@ func TestRepository_ListRoles_Multiple_Scopes(t *testing.T) { repo := TestRepo(t, conn, wrapper) org, proj := TestScopes(t, repo) - db.TestDeleteWhere(t, conn, func() interface{} { i := allocRole(); return &i }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { i := allocRole(); return &i }(), "1=1") const numPerScope = 10 var total int diff --git a/internal/iam/repository_scope.go b/internal/iam/repository_scope.go index 733cd16437..6a31df27e5 100644 --- a/internal/iam/repository_scope.go +++ b/internal/iam/repository_scope.go @@ -55,7 +55,7 @@ func (r *Repository) CreateScope(ctx context.Context, s *Scope, userId string, o var scopePublicId string var scopeMetadata oplog.Metadata - var scopeRaw interface{} + var scopeRaw any { scopeType := scope.Map[s.Type] if opts.withPublicId != "" { @@ -82,7 +82,7 @@ func (r *Repository) CreateScope(ctx context.Context, s *Scope, userId string, o var adminRolePublicId string var adminRoleMetadata oplog.Metadata var adminRole *Role - var adminRoleRaw interface{} + var adminRoleRaw any switch { case userId == "", userId == "u_anon", @@ -123,7 +123,7 @@ func (r *Repository) CreateScope(ctx context.Context, s *Scope, userId string, o var defaultRolePublicId string var defaultRoleMetadata oplog.Metadata var defaultRole *Role - var defaultRoleRaw interface{} + var defaultRoleRaw any if !opts.withSkipDefaultRoleCreation { defaultRole, err = NewRole(scopePublicId) if err != nil { @@ -224,7 +224,7 @@ func (r *Repository) CreateScope(ctx context.Context, s *Scope, userId string, o return errors.Wrap(ctx, err, op, errors.WithMsg("unable to create in memory role grant")) } roleGrantOplogMsgs := make([]*oplog.Message, 0, 1) - if err := w.CreateItems(ctx, []interface{}{roleGrant}, db.NewOplogMsgs(&roleGrantOplogMsgs)); err != nil { + if err := w.CreateItems(ctx, []any{roleGrant}, db.NewOplogMsgs(&roleGrantOplogMsgs)); err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg("unable to add grants")) } msgs = append(msgs, roleGrantOplogMsgs...) @@ -234,7 +234,7 @@ func (r *Repository) CreateScope(ctx context.Context, s *Scope, userId string, o return errors.Wrap(ctx, err, op, errors.WithMsg("unable to create in memory role user")) } roleUserOplogMsgs := make([]*oplog.Message, 0, 1) - if err := w.CreateItems(ctx, []interface{}{rolePrincipal}, db.NewOplogMsgs(&roleUserOplogMsgs)); err != nil { + if err := w.CreateItems(ctx, []any{rolePrincipal}, db.NewOplogMsgs(&roleUserOplogMsgs)); err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg("unable to add grants")) } msgs = append(msgs, roleUserOplogMsgs...) @@ -283,7 +283,7 @@ func (r *Repository) CreateScope(ctx context.Context, s *Scope, userId string, o // Grants { - grants := []interface{}{} + grants := []any{} switch s.Type { case scope.Project.String(): @@ -334,7 +334,7 @@ func (r *Repository) CreateScope(ctx context.Context, s *Scope, userId string, o // Principals { - principals := []interface{}{} + principals := []any{} userId := "u_anon" if s.Type == scope.Project.String() { userId = "u_auth" @@ -395,7 +395,7 @@ func (r *Repository) UpdateScope(ctx context.Context, scope *Scope, version uint } var dbMask, nullFields []string dbMask, nullFields = dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ "name": scope.Name, "description": scope.Description, "PrimaryAuthMethodId": scope.PrimaryAuthMethodId, // gorm: it's important that the field start with a capital letter. @@ -463,7 +463,7 @@ func (r *Repository) ListScopes(ctx context.Context, withParentIds []string, opt return nil, errors.New(ctx, errors.InvalidParameter, op, "missing parent id") } var items []*Scope - err := r.list(ctx, &items, "parent_id in (?)", []interface{}{withParentIds}, opt...) + err := r.list(ctx, &items, "parent_id in (?)", []any{withParentIds}, opt...) if err != nil { return nil, errors.Wrap(ctx, err, op) } @@ -476,7 +476,7 @@ func (r *Repository) ListScopesRecursively(ctx context.Context, rootScopeId stri const op = "iam.(Repository).ListRecursively" var scopes []*Scope var where string - var args []interface{} + var args []any switch { case rootScopeId == scope.Global.String(): // Nothing -- we want all scopes diff --git a/internal/iam/repository_scope_test.go b/internal/iam/repository_scope_test.go index d271053064..4fb25cb914 100644 --- a/internal/iam/repository_scope_test.go +++ b/internal/iam/repository_scope_test.go @@ -448,7 +448,7 @@ func TestRepository_UpdateScope(t *testing.T) { for _, f := range tt.wantNullFields { where = fmt.Sprintf("%s and %s is null", where, f) } - err = rw.LookupWhere(context.Background(), &foundScope, where, []interface{}{org.PublicId}) + err = rw.LookupWhere(context.Background(), &foundScope, where, []any{org.PublicId}) require.NoError(err) assert.Equal(org.PublicId, foundScope.PublicId) assert.Equal(tt.wantName, foundScope.Name) @@ -520,7 +520,7 @@ func Test_Repository_ListScopes(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { i := AllocScope(); ; return &i }(), "type = 'org'") + db.TestDeleteWhere(t, conn, func() any { i := AllocScope(); ; return &i }(), "type = 'org'") testOrgs := []*Scope{} for i := 0; i < tt.createCnt; i++ { @@ -544,7 +544,7 @@ func TestRepository_ListScopes_Multiple_Scopes(t *testing.T) { wrapper := db.TestWrapper(t) repo := TestRepo(t, conn, wrapper) - db.TestDeleteWhere(t, conn, func() interface{} { i := AllocScope(); return &i }(), "public_id != 'global'") + db.TestDeleteWhere(t, conn, func() any { i := AllocScope(); return &i }(), "public_id != 'global'") const numPerScope = 10 var total int diff --git a/internal/iam/repository_test.go b/internal/iam/repository_test.go index 7b27a264dc..c24c620f9e 100644 --- a/internal/iam/repository_test.go +++ b/internal/iam/repository_test.go @@ -126,11 +126,11 @@ func Test_Repository_create(t *testing.T) { assert.True(proto.Equal(foundScope, retScope.(*Scope))) var metadata store.Metadata - err = rw.LookupWhere(context.Background(), &metadata, "key = ? and value = ?", []interface{}{"resource-public-id", s.PublicId}) + err = rw.LookupWhere(context.Background(), &metadata, "key = ? and value = ?", []any{"resource-public-id", s.PublicId}) require.NoError(err) var foundEntry oplog.Entry - err = rw.LookupWhere(context.Background(), &foundEntry, "id = ?", []interface{}{metadata.EntryId}) + err = rw.LookupWhere(context.Background(), &foundEntry, "id = ?", []any{metadata.EntryId}) assert.NoError(err) }) t.Run("nil-resource", func(t *testing.T) { @@ -315,7 +315,7 @@ func TestRepository_update(t *testing.T) { for _, f := range tt.args.setToNullPaths { where = fmt.Sprintf("%s and %s is null", where, f) } - err = rw.LookupWhere(context.Background(), &foundResource, where, []interface{}{tt.args.resource.GetPublicId()}) + err = rw.LookupWhere(context.Background(), &foundResource, where, []any{tt.args.resource.GetPublicId()}) require.NoError(err) assert.Equal(tt.args.resource.GetPublicId(), foundResource.GetPublicId()) assert.Equal(tt.wantName, foundResource.GetName()) diff --git a/internal/iam/repository_user.go b/internal/iam/repository_user.go index c743edb768..fdcce699a8 100644 --- a/internal/iam/repository_user.go +++ b/internal/iam/repository_user.go @@ -83,7 +83,7 @@ func (r *Repository) UpdateUser(ctx context.Context, user *User, version uint32, } var dbMask, nullFields []string dbMask, nullFields = dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ "name": user.Name, "description": user.Description, }, @@ -347,7 +347,7 @@ func (r *Repository) getUserWithAccount(ctx context.Context, withAccountId strin if withAccountId == "" { return nil, errors.New(ctx, errors.InvalidParameter, op, "missing account id") } - rows, err := r.reader.Query(ctx, whereUserAccount, []interface{}{withAccountId}) + rows, err := r.reader.Query(ctx, whereUserAccount, []any{withAccountId}) if err != nil { return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to query account %s", withAccountId))) } @@ -375,7 +375,7 @@ func (r *Repository) ListUserAccounts(ctx context.Context, userId string, opt .. return nil, errors.New(ctx, errors.InvalidParameter, op, "missing user id") } var accounts []*authAccount - if err := r.list(ctx, &accounts, "iam_user_id = ?", []interface{}{userId}, opt...); err != nil { + if err := r.list(ctx, &accounts, "iam_user_id = ?", []any{userId}, opt...); err != nil { return nil, errors.Wrap(ctx, err, op) } if len(accounts) == 0 { @@ -795,7 +795,7 @@ func associationChanges(ctx context.Context, reader db.Reader, userId string, ac } query := fmt.Sprintf(accountChangesQuery, inClause) - var params []interface{} + var params []any for _, v := range accountIds { params = append(params, v) } @@ -877,7 +877,7 @@ func (r *Repository) getUsers(ctx context.Context, userId string, scopeIds []str } dbArgs = append(dbArgs, db.WithLimit(limit)) - var args []interface{} + var args []any var where []string switch { case userId != "": diff --git a/internal/iam/repository_user_test.go b/internal/iam/repository_user_test.go index b8e7649256..7ab72b41f4 100644 --- a/internal/iam/repository_user_test.go +++ b/internal/iam/repository_user_test.go @@ -648,7 +648,7 @@ func TestRepository_ListUsers(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { u := iam.AllocUser(); return &u }(), "public_id != 'u_anon' and public_id != 'u_auth' and public_id != 'u_recovery'") + db.TestDeleteWhere(t, conn, func() any { u := iam.AllocUser(); return &u }(), "public_id != 'u_anon' and public_id != 'u_auth' and public_id != 'u_recovery'") testUsers := []*iam.User{} wantUserInfo := map[string]userInfo{} for i := 0; i < tt.createCnt; i++ { @@ -693,7 +693,7 @@ func TestRepository_ListUsers_Multiple_Scopes(t *testing.T) { repo := iam.TestRepo(t, conn, wrapper) org, _ := iam.TestScopes(t, repo) - db.TestDeleteWhere(t, conn, func() interface{} { i := iam.AllocUser(); return &i }(), "public_id != 'u_anon' and public_id != 'u_auth' and public_id != 'u_recovery'") + db.TestDeleteWhere(t, conn, func() any { i := iam.AllocUser(); return &i }(), "public_id != 'u_anon' and public_id != 'u_auth' and public_id != 'u_recovery'") const numPerScope = 10 var total int = 3 // anon, auth, recovery @@ -902,7 +902,7 @@ func TestRepository_AssociateAccounts(t *testing.T) { user := iam.TestUser(t, repo, org.PublicId) createAccountsFn := func(prefix string) []string { - db.TestDeleteWhere(t, conn, func() interface{} { i := allocAuthAccount(); return &i }(), "iam_user_id = ?", user.PublicId) + db.TestDeleteWhere(t, conn, func() any { i := allocAuthAccount(); return &i }(), "iam_user_id = ?", user.PublicId) results := []string{} for i := 0; i < 5; i++ { authMethod := oidc.TestAuthMethod(t, conn, databaseWrapper, org.PublicId, oidc.ActivePrivateState, fmt.Sprintf("%s-alice-rp-%d", prefix, i), "fido", @@ -1072,7 +1072,7 @@ func TestRepository_DisassociateAccounts(t *testing.T) { user := iam.TestUser(t, repo, org.PublicId) createAccountsFn := func(prefix string) []string { - db.TestDeleteWhere(t, conn, func() interface{} { a := allocAuthAccount(); return &a }(), "iam_user_id = ?", user.PublicId) + db.TestDeleteWhere(t, conn, func() any { a := allocAuthAccount(); return &a }(), "iam_user_id = ?", user.PublicId) results := []string{} for i := 0; i < 1; i++ { authMethod := oidc.TestAuthMethod(t, conn, databaseWrapper, org.PublicId, oidc.ActivePrivateState, fmt.Sprintf("%s-alice-rp-%d", prefix, i), "fido", @@ -1220,7 +1220,7 @@ func TestRepository_SetAssociatedAccounts(t *testing.T) { user := iam.TestUser(t, repo, org.PublicId) createAccountsFn := func(prefix string) []string { - db.TestDeleteWhere(t, conn, func() interface{} { i := allocAuthAccount(); return &i }(), "iam_user_id = ?", user.PublicId) + db.TestDeleteWhere(t, conn, func() any { i := allocAuthAccount(); return &i }(), "iam_user_id = ?", user.PublicId) results := []string{} for i := 0; i < 1; i++ { authMethod := oidc.TestAuthMethod(t, conn, databaseWrapper, org.PublicId, oidc.ActivePrivateState, fmt.Sprintf("%s-alice-rp-%d", prefix, i), "fido", @@ -1382,7 +1382,7 @@ func TestRepository_SetAssociatedAccounts(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { a := allocAuthAccount(); return &a }(), "iam_user_id = ?", user.PublicId) + db.TestDeleteWhere(t, conn, func() any { a := allocAuthAccount(); return &a }(), "iam_user_id = ?", user.PublicId) accountIds, changes := tt.args.accountIdsFn() sort.Strings(accountIds) diff --git a/internal/iam/resource.go b/internal/iam/resource.go index 02e90d06d4..ac68098e8d 100644 --- a/internal/iam/resource.go +++ b/internal/iam/resource.go @@ -36,7 +36,7 @@ type Resource interface { } type Cloneable interface { - Clone() interface{} + Clone() any } // ResourceWithScope defines an interface for Resources that have a scope @@ -69,7 +69,7 @@ func LookupScope(ctx context.Context, reader db.Reader, resource ResourceWithSco } } var p Scope - if err := reader.LookupWhere(ctx, &p, "public_id = ?", []interface{}{resource.GetScopeId()}); err != nil { + if err := reader.LookupWhere(ctx, &p, "public_id = ?", []any{resource.GetScopeId()}); err != nil { return nil, errors.Wrap(ctx, err, op) } return &p, nil diff --git a/internal/iam/role.go b/internal/iam/role.go index 49561f441e..33e6931bc4 100644 --- a/internal/iam/role.go +++ b/internal/iam/role.go @@ -55,7 +55,7 @@ func allocRole() Role { } // Clone creates a clone of the Role. -func (r *Role) Clone() interface{} { +func (r *Role) Clone() any { cp := proto.Clone(r.Role) return &Role{ Role: cp.(*store.Role), diff --git a/internal/iam/role_grant.go b/internal/iam/role_grant.go index 1964010677..07116a63cf 100644 --- a/internal/iam/role_grant.go +++ b/internal/iam/role_grant.go @@ -58,7 +58,7 @@ func allocRoleGrant() RoleGrant { } // Clone creates a clone of the RoleGrant -func (g *RoleGrant) Clone() interface{} { +func (g *RoleGrant) Clone() any { cp := proto.Clone(g.RoleGrant) return &RoleGrant{ RoleGrant: cp.(*store.RoleGrant), diff --git a/internal/iam/role_grant_test.go b/internal/iam/role_grant_test.go index 7963f3868b..80328ce457 100644 --- a/internal/iam/role_grant_test.go +++ b/internal/iam/role_grant_test.go @@ -86,7 +86,7 @@ func TestRoleGrant_Create(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { a := allocRoleGrant(); return &a }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { a := allocRoleGrant(); return &a }(), "1=1") got, err := NewRoleGrant(tt.args.roleId, tt.args.grant, tt.args.opt...) if tt.wantErr { require.Error(err) diff --git a/internal/iam/scope.go b/internal/iam/scope.go index a2101ef371..4a9bd0a7b7 100644 --- a/internal/iam/scope.go +++ b/internal/iam/scope.go @@ -94,7 +94,7 @@ func AllocScope() Scope { } // Clone creates a clone of the Scope -func (s *Scope) Clone() interface{} { +func (s *Scope) Clone() any { cp := proto.Clone(s.Scope) return &Scope{ Scope: cp.(*store.Scope), @@ -185,11 +185,11 @@ func (s *Scope) GetScope(ctx context.Context, r db.Reader) (*Scope, error) { // for all scopes which are not global, and the global case was // handled at HANDLE_GLOBAL where := "public_id in (select parent_id from iam_scope where public_id = ?)" - if err := r.LookupWhere(ctx, &p, where, []interface{}{s.PublicId}); err != nil { + if err := r.LookupWhere(ctx, &p, where, []any{s.PublicId}); err != nil { return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to lookup parent public id from public id")) } default: - if err := r.LookupWhere(ctx, &p, "public_id = ?", []interface{}{s.ParentId}); err != nil { + if err := r.LookupWhere(ctx, &p, "public_id = ?", []any{s.ParentId}); err != nil { return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to lookup parent from public id")) } } diff --git a/internal/iam/testing.go b/internal/iam/testing.go index e5e7828639..0ac089d9d6 100644 --- a/internal/iam/testing.go +++ b/internal/iam/testing.go @@ -339,7 +339,7 @@ func testAuthMethod(t testing.TB, conn *db.DB, scopeId string) string { require.NoError(err) rw := db.New(conn) - _, err = rw.Exec(context.Background(), insertAuthMethod, []interface{}{id, scopeId}) + _, err = rw.Exec(context.Background(), insertAuthMethod, []any{id, scopeId}) require.NoError(err) return id } diff --git a/internal/iam/user.go b/internal/iam/user.go index 5430ff7b9b..0feb45a8be 100644 --- a/internal/iam/user.go +++ b/internal/iam/user.go @@ -57,7 +57,7 @@ func AllocUser() User { } // Clone creates a clone of the User -func (u *User) Clone() interface{} { +func (u *User) Clone() any { cp := proto.Clone(u.User) return &User{ User: cp.(*store.User), diff --git a/internal/kms/kms.go b/internal/kms/kms.go index f2e3d28c67..949cd466b7 100644 --- a/internal/kms/kms.go +++ b/internal/kms/kms.go @@ -241,7 +241,7 @@ func stdNewKmsPurposes() []wrappingKms.KeyPurpose { return purposes } -func isNil(i interface{}) bool { +func isNil(i any) bool { if i == nil { return true } diff --git a/internal/kms/testing.go b/internal/kms/testing.go index 1cab48eba6..0d2311467a 100644 --- a/internal/kms/testing.go +++ b/internal/kms/testing.go @@ -26,12 +26,12 @@ func TestKms(t testing.TB, conn *db.DB, rootWrapper wrapping.Wrapper) *Kms { // TestKmsDeleteKeyPurpose allows you to delete a KeyPurpose for testing. func TestKmsDeleteKeyPurpose(t testing.TB, conn *db.DB, purpose KeyPurpose) { - db.TestDeleteWhere(t, conn, func() interface{} { i := dataKey{}; return &i }(), fmt.Sprintf("purpose='%s'", purpose.String())) + db.TestDeleteWhere(t, conn, func() any { i := dataKey{}; return &i }(), fmt.Sprintf("purpose='%s'", purpose.String())) } // TestKmsDeleteAllKeys allows you to delete all the keys for testing. func TestKmsDeleteAllKeys(t testing.TB, conn *db.DB) { - db.TestDeleteWhere(t, conn, func() interface{} { i := rootKey{}; return &i }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { i := rootKey{}; return &i }(), "1=1") } type dataKey struct{} diff --git a/internal/libs/patchstruct/patchstruct.go b/internal/libs/patchstruct/patchstruct.go index 678198a610..9b47fcb28a 100644 --- a/internal/libs/patchstruct/patchstruct.go +++ b/internal/libs/patchstruct/patchstruct.go @@ -72,16 +72,16 @@ func PatchBytes(dst, src []byte) ([]byte, error) { return result, nil } -func patchM(dst, src map[string]interface{}) map[string]interface{} { +func patchM(dst, src map[string]any) map[string]any { for k, v := range src { switch x := v.(type) { - case map[string]interface{}: - if y, ok := dst[k].(map[string]interface{}); ok { + case map[string]any: + if y, ok := dst[k].(map[string]any); ok { // If the value in dst a map, continue to patch dst[k] = patchM(y, x) } else { // Overwrite after stripping out keys to nil values - newX := patchM(make(map[string]interface{}), x) + newX := patchM(make(map[string]any), x) dst[k] = newX } diff --git a/internal/libs/patchstruct/patchstruct_test.go b/internal/libs/patchstruct/patchstruct_test.go index 7eb4118013..79ec443728 100644 --- a/internal/libs/patchstruct/patchstruct_test.go +++ b/internal/libs/patchstruct/patchstruct_test.go @@ -14,65 +14,65 @@ import ( type testCase struct { name string - dst map[string]interface{} - src map[string]interface{} - expected map[string]interface{} + dst map[string]any + src map[string]any + expected map[string]any } var testCases = []testCase{ { name: "merge", - dst: map[string]interface{}{ + dst: map[string]any{ "foo": "bar", }, - src: map[string]interface{}{ + src: map[string]any{ "baz": "qux", }, - expected: map[string]interface{}{ + expected: map[string]any{ "foo": "bar", "baz": "qux", }, }, { name: "overwrite", - dst: map[string]interface{}{ + dst: map[string]any{ "foo": "bar", }, - src: map[string]interface{}{ + src: map[string]any{ "foo": "baz", }, - expected: map[string]interface{}{ + expected: map[string]any{ "foo": "baz", }, }, { name: "delete", - dst: map[string]interface{}{ + dst: map[string]any{ "foo": "bar", "baz": "qux", }, - src: map[string]interface{}{ + src: map[string]any{ "baz": nil, }, - expected: map[string]interface{}{ + expected: map[string]any{ "foo": "bar", }, }, { name: "recursive", - dst: map[string]interface{}{ - "nested": map[string]interface{}{ + dst: map[string]any{ + "nested": map[string]any{ "a": "b", }, "foo": "bar", }, - src: map[string]interface{}{ - "nested": map[string]interface{}{ + src: map[string]any{ + "nested": map[string]any{ "c": "d", }, }, - expected: map[string]interface{}{ - "nested": map[string]interface{}{ + expected: map[string]any{ + "nested": map[string]any{ "a": "b", "c": "d", }, @@ -82,40 +82,40 @@ var testCases = []testCase{ { name: "nested with nil", dst: nil, - src: map[string]interface{}{ + src: map[string]any{ "a": "b", - "nested": map[string]interface{}{ + "nested": map[string]any{ "c": "d", "e": nil, }, "f": nil, }, - expected: map[string]interface{}{ + expected: map[string]any{ "a": "b", - "nested": map[string]interface{}{ + "nested": map[string]any{ "c": "d", }, }, }, { name: "overwrite with map in src", - dst: map[string]interface{}{ + dst: map[string]any{ "foo": "bar", }, - src: map[string]interface{}{ - "foo": map[string]interface{}{ + src: map[string]any{ + "foo": map[string]any{ "a": "b", }, }, - expected: map[string]interface{}{ - "foo": map[string]interface{}{ + expected: map[string]any{ + "foo": map[string]any{ "a": "b", }, }, }, { name: "nil src", - dst: map[string]interface{}{ + dst: map[string]any{ "foo": "bar", }, src: nil, @@ -124,21 +124,21 @@ var testCases = []testCase{ { name: "nil dst", dst: nil, - src: map[string]interface{}{ + src: map[string]any{ "foo": "bar", }, - expected: map[string]interface{}{ + expected: map[string]any{ "foo": "bar", }, }, { name: "nil dst with src nil value", dst: nil, - src: map[string]interface{}{ + src: map[string]any{ "foo": "bar", "fiz": nil, }, - expected: map[string]interface{}{ + expected: map[string]any{ "foo": "bar", }, }, @@ -163,7 +163,7 @@ func TestPatchStruct(t *testing.T) { actual := PatchStruct(dst, src) require.Empty(cmp.Diff(mustStruct(tc.expected), actual, cmpopts.IgnoreUnexported(structpb.Struct{}, structpb.Value{}), - cmpopts.SortSlices(func(x, y interface{}) bool { + cmpopts.SortSlices(func(x, y any) bool { return x.(*host.IpAddress).Address < y.(*host.IpAddress).Address }))) require.Equal(dstOrig, dst) @@ -195,7 +195,7 @@ func TestPatchBytesErr(t *testing.T) { }) } -func mustStruct(in map[string]interface{}) *structpb.Struct { +func mustStruct(in map[string]any) *structpb.Struct { out, err := structpb.NewStruct(in) if err != nil { panic(err) @@ -204,7 +204,7 @@ func mustStruct(in map[string]interface{}) *structpb.Struct { return out } -func mustMarshal(in map[string]interface{}) []byte { +func mustMarshal(in map[string]any) []byte { b, err := proto.Marshal(mustStruct(in)) if err != nil { panic(err) diff --git a/internal/observability/event/cloudevents_formatter_node.go b/internal/observability/event/cloudevents_formatter_node.go index d457703f25..68bf0fa966 100644 --- a/internal/observability/event/cloudevents_formatter_node.go +++ b/internal/observability/event/cloudevents_formatter_node.go @@ -106,8 +106,8 @@ func (f *cloudEventsFormatterFilter) Rotate(w wrapping.Wrapper, _ ...Option) err return nil } -func newPredicate(allow, deny []*filter) func(ctx context.Context, ce interface{}) (bool, error) { - return func(ctx context.Context, ce interface{}) (bool, error) { +func newPredicate(allow, deny []*filter) func(ctx context.Context, ce any) (bool, error) { + return func(ctx context.Context, ce any) (bool, error) { if len(allow) == 0 && len(deny) == 0 { return true, nil } @@ -154,7 +154,7 @@ func newFilter(f string) (*filter, error) { // Match returns if the provided interface matches the filter. If the filter // does not match the structure of the object being Matched, false is returned. -func (f *filter) Match(item interface{}) bool { +func (f *filter) Match(item any) bool { if f.eval == nil { return true } diff --git a/internal/observability/event/cloudevents_formatter_node_test.go b/internal/observability/event/cloudevents_formatter_node_test.go index 2aee2598d9..4a28643570 100644 --- a/internal/observability/event/cloudevents_formatter_node_test.go +++ b/internal/observability/event/cloudevents_formatter_node_test.go @@ -162,7 +162,7 @@ func TestNode_Process(t *testing.T) { n *cloudEventsFormatterFilter e *eventlogger.Event format cloudevents.Format - predicate func(ctx context.Context, ce interface{}) (bool, error) + predicate func(ctx context.Context, ce any) (bool, error) wantCloudEvent *cloudevents.Event wantText string wantIsError error diff --git a/internal/observability/event/context.go b/internal/observability/event/context.go index e788b7dc5f..3c9b1c1d49 100644 --- a/internal/observability/event/context.go +++ b/internal/observability/event/context.go @@ -257,7 +257,7 @@ func addCtxOptions(ctx context.Context, opt ...Option) ([]Option, error) { // // This function should never be used when sending events while // handling API requests. -func WriteSysEvent(ctx context.Context, caller Op, msg string, args ...interface{}) { +func WriteSysEvent(ctx context.Context, caller Op, msg string, args ...any) { const op = "event.WriteSysEvent" info := ConvertArgs(args...) @@ -265,7 +265,7 @@ func WriteSysEvent(ctx context.Context, caller Op, msg string, args ...interface return } if info == nil { - info = make(map[string]interface{}, 1) + info = make(map[string]any, 1) } info[msgField] = msg @@ -339,7 +339,7 @@ const MissingKey = "EXTRA_VALUE_AT_END" // ConvertArgs will convert the key/value pair args to a map. If the args // provided are an odd number (they're missing a key in their key/value pairs) // then MissingKey is used to the missing key. -func ConvertArgs(args ...interface{}) map[string]interface{} { +func ConvertArgs(args ...any) map[string]any { if len(args) == 0 { return nil } @@ -348,7 +348,7 @@ func ConvertArgs(args ...interface{}) map[string]interface{} { args = append(args[:len(args)-1], MissingKey, extra) } - m := map[string]interface{}{} + m := map[string]any{} for i := 0; i < len(args); i = i + 2 { var key string switch st := args[i].(type) { diff --git a/internal/observability/event/context_test.go b/internal/observability/event/context_test.go index 98fa2726e9..98f6707787 100644 --- a/internal/observability/event/context_test.go +++ b/internal/observability/event/context_test.go @@ -281,28 +281,28 @@ func Test_WriteObservation(t *testing.T) { noEventId.Id = "" type observationPayload struct { - header []interface{} - details []interface{} + header []any + details []any } testPayloads := []observationPayload{ { - header: []interface{}{"name", "bar"}, + header: []any{"name", "bar"}, }, { - header: []interface{}{"list", []string{"1", "2"}}, + header: []any{"list", []string{"1", "2"}}, }, { - details: []interface{}{"file", "temp-file.txt"}, + details: []any{"file", "temp-file.txt"}, }, } - testWantHeader := map[string]interface{}{ + testWantHeader := map[string]any{ "name": "bar", "list": []string{"1", "2"}, } - testWantDetails := map[string]interface{}{ + testWantDetails := map[string]any{ "file": "temp-file.txt", } @@ -311,8 +311,8 @@ func Test_WriteObservation(t *testing.T) { noOperation bool noFlush bool observationPayload []observationPayload - header map[string]interface{} - details map[string]interface{} + header map[string]any + details map[string]any ctx context.Context observationSinkFileName string setup func() error @@ -326,10 +326,10 @@ func Test_WriteObservation(t *testing.T) { ctx: testCtxNoEventInfoId, observationPayload: []observationPayload{ { - header: []interface{}{"name", "bar"}, + header: []any{"name", "bar"}, }, }, - header: map[string]interface{}{ + header: map[string]any{ "name": "bar", }, observationSinkFileName: c.AllEvents.Name(), @@ -375,10 +375,10 @@ func Test_WriteObservation(t *testing.T) { ctx: context.Background(), observationPayload: []observationPayload{ { - header: []interface{}{"name", "bar"}, + header: []any{"name", "bar"}, }, }, - header: map[string]interface{}{ + header: map[string]any{ "name": "bar", }, observationSinkFileName: c.AllEvents.Name(), @@ -397,10 +397,10 @@ func Test_WriteObservation(t *testing.T) { }(), observationPayload: []observationPayload{ { - header: []interface{}{"name", "bar"}, + header: []any{"name", "bar"}, }, }, - header: map[string]interface{}{ + header: map[string]any{ "name": "bar", }, observationSinkFileName: c.AllEvents.Name(), @@ -478,7 +478,7 @@ func Test_WriteObservation(t *testing.T) { testCtx, err = event.NewRequestInfoContext(testCtx, info) require.NoError(err) - hdr := map[string]interface{}{ + hdr := map[string]any{ "list": []string{"1", "2"}, } require.NoError(event.WriteObservation(testCtx, "not-enabled", event.WithHeader(hdr), event.WithFlush())) @@ -496,31 +496,31 @@ func Test_Filtering(t *testing.T) { name string allow []string deny []string - hdr []interface{} + hdr []any found bool }{ { name: "allowed", allow: []string{`"/data/list" contains "1"`}, - hdr: []interface{}{"list", []string{"1", "2"}}, + hdr: []any{"list", []string{"1", "2"}}, found: true, }, { name: "not-allowed", allow: []string{`"/data/list" contains "22"`}, - hdr: []interface{}{"list", []string{"1", "2"}}, + hdr: []any{"list", []string{"1", "2"}}, found: false, }, { name: "deny", deny: []string{`"/data/list" contains "1"`}, - hdr: []interface{}{"list", []string{"1", "2"}}, + hdr: []any{"list", []string{"1", "2"}}, found: false, }, { name: "not-deny", deny: []string{`"/data/list" contains "22"`}, - hdr: []interface{}{"list", []string{"1", "2"}}, + hdr: []any{"list", []string{"1", "2"}}, found: true, }, } @@ -566,7 +566,7 @@ func Test_DefaultEventerConfig(t *testing.T) { }) } -func testObservationJsonFromCtx(t *testing.T, ctx context.Context, caller event.Op, got *cloudevents.Event, hdr, details map[string]interface{}) []byte { +func testObservationJsonFromCtx(t *testing.T, ctx context.Context, caller event.Op, got *cloudevents.Event, hdr, details map[string]any) []byte { t.Helper() require := require.New(t) @@ -580,24 +580,24 @@ func testObservationJsonFromCtx(t *testing.T, ctx context.Context, caller event. SpecVersion: got.SpecVersion, Type: got.Type, DataContentType: got.DataContentType, - Data: map[string]interface{}{ + Data: map[string]any{ event.RequestInfoField: reqInfo, event.VersionField: testObservationVersion, }, } if hdr != nil { - h := j.Data.(map[string]interface{}) + h := j.Data.(map[string]any) for k, v := range hdr { h[k] = v } } if details != nil { details[event.OpField] = string(caller) - d := got.Data.(map[string]interface{})[event.DetailsField].([]interface{})[0].(map[string]interface{}) - j.Data.(map[string]interface{})[event.DetailsField] = []struct { - CreatedAt string `json:"created_at"` - Type string `json:"type"` - Payload map[string]interface{} `json:"payload"` + d := got.Data.(map[string]any)[event.DetailsField].([]any)[0].(map[string]any) + j.Data.(map[string]any)[event.DetailsField] = []struct { + CreatedAt string `json:"created_at"` + Type string `json:"type"` + Payload map[string]any `json:"payload"` }{ { CreatedAt: d[event.CreatedAtField].(string), @@ -896,9 +896,9 @@ func Test_WriteAudit(t *testing.T) { DataContentType: gotAudit.DataContentType, Time: gotAudit.Time, Type: "audit", - Data: map[string]interface{}{ + Data: map[string]any{ "auth": tt.wantAudit.Auth, - "id": gotAudit.Data.(map[string]interface{})["id"], + "id": gotAudit.Data.(map[string]any)["id"], "timestamp": now, "request": tt.wantAudit.Request, "type": apiRequest, @@ -906,13 +906,13 @@ func Test_WriteAudit(t *testing.T) { }, } if tt.wantAudit.Id != "" { - wantEvent.Data.(map[string]interface{})["id"] = tt.wantAudit.Id - wantEvent.Data.(map[string]interface{})["request_info"] = event.RequestInfo{ - Id: gotAudit.Data.(map[string]interface{})["request_info"].(map[string]interface{})["id"].(string), + wantEvent.Data.(map[string]any)["id"] = tt.wantAudit.Id + wantEvent.Data.(map[string]any)["request_info"] = event.RequestInfo{ + Id: gotAudit.Data.(map[string]any)["request_info"].(map[string]any)["id"].(string), } } if tt.wantAudit.Response != nil { - wantEvent.Data.(map[string]interface{})["response"] = tt.wantAudit.Response + wantEvent.Data.(map[string]any)["response"] = tt.wantAudit.Response } wantJson, err := json.Marshal(wantEvent) require.NoError(err) @@ -1086,10 +1086,10 @@ func Test_WriteError(t *testing.T) { err = json.Unmarshal(b, gotError) require.NoErrorf(err, "json: %s", string(b)) - if _, ok := gotError.Data.(map[string]interface{})["error_fields"].(map[string]interface{})["Msg"]; ok { + if _, ok := gotError.Data.(map[string]any)["error_fields"].(map[string]any)["Msg"]; ok { actualError := fakeError{ - Msg: gotError.Data.(map[string]interface{})["error_fields"].(map[string]interface{})["Msg"].(string), - Code: gotError.Data.(map[string]interface{})["error_fields"].(map[string]interface{})["Code"].(string), + Msg: gotError.Data.(map[string]any)["error_fields"].(map[string]any)["Msg"].(string), + Code: gotError.Data.(map[string]any)["error_fields"].(map[string]any)["Code"].(string), } assert.Equal(tt.e, &actualError) } @@ -1120,7 +1120,7 @@ func Test_WriteSysEvent(t *testing.T) { tests := []struct { name string ctx context.Context - data []interface{} + data []any msg string info *event.RequestInfo setup func() error @@ -1138,14 +1138,14 @@ func Test_WriteSysEvent(t *testing.T) { name: "missing-caller", ctx: ctx, msg: "hello", - data: []interface{}{"data", "test-data"}, + data: []any{"data", "test-data"}, noOperation: true, }, { name: "syseventer-not-initialized", ctx: context.Background(), msg: "hello", - data: []interface{}{"data", "test-data"}, + data: []any{"data", "test-data"}, sinkFileName: c.AllEvents.Name(), noOutput: true, }, @@ -1153,7 +1153,7 @@ func Test_WriteSysEvent(t *testing.T) { name: "use-syseventer", ctx: context.Background(), msg: "hello", - data: []interface{}{"data", "test-data", event.ServerName, "test-server", event.ServerAddress, "localhost"}, + data: []any{"data", "test-data", event.ServerName, "test-server", event.ServerAddress, "localhost"}, setup: func() error { return event.InitSysEventer(testLogger, testLock, "use-syseventer", event.WithEventerConfig(&c.EventerConfig)) }, @@ -1168,7 +1168,7 @@ func Test_WriteSysEvent(t *testing.T) { return ctx }(), msg: "hello", - data: []interface{}{"data", "test-data", event.ServerName, "test-server", event.ServerAddress, "localhost"}, + data: []any{"data", "test-data", event.ServerName, "test-server", event.ServerAddress, "localhost"}, setup: func() error { return event.InitSysEventer(testLogger, testLock, "use-syseventer", event.WithEventerConfig(&c.EventerConfig)) }, @@ -1207,7 +1207,7 @@ func Test_WriteSysEvent(t *testing.T) { expected := event.ConvertArgs(tt.data...) expected["msg"] = tt.msg - assert.Equal(expected, gotSysEvent.Data.(map[string]interface{})["data"].(map[string]interface{})) + assert.Equal(expected, gotSysEvent.Data.(map[string]any)["data"].(map[string]any)) } }) } @@ -1216,40 +1216,40 @@ func Test_WriteSysEvent(t *testing.T) { func TestConvertArgs(t *testing.T) { tests := []struct { name string - args []interface{} - want map[string]interface{} + args []any + want map[string]any }{ { name: "no-args", - args: []interface{}{}, + args: []any{}, want: nil, }, { name: "nil-first-arg", - args: []interface{}{nil}, - want: map[string]interface{}{ + args: []any{nil}, + want: map[string]any{ event.MissingKey: nil, }, }, { name: "odd-number-of-args", - args: []interface{}{1, 2, 3}, - want: map[string]interface{}{ + args: []any{1, 2, 3}, + want: map[string]any{ "1": 2, event.MissingKey: 3, }, }, { name: "struct-key", - args: []interface{}{[]struct{ name string }{{name: "alice"}}, 1}, - want: map[string]interface{}{ + args: []any{[]struct{ name string }{{name: "alice"}}, 1}, + want: map[string]any{ "[{alice}]": 1, }, }, { name: "test-key-with-stringer", - args: []interface{}{testIntKeyWithStringer(11), "eleven"}, - want: map[string]interface{}{ + args: []any{testIntKeyWithStringer(11), "eleven"}, + want: map[string]any{ "*11*": "eleven", }, }, diff --git a/internal/observability/event/event_audit.go b/internal/observability/event/event_audit.go index 48e6d38de3..c349120942 100644 --- a/internal/observability/event/event_audit.go +++ b/internal/observability/event/event_audit.go @@ -93,7 +93,7 @@ func (a *audit) FlushEvent() bool { // ComposedFrom is part of the eventlogger.Gatable interface. It's important to // remember that the receiver will always be nil when this is called by the eventlogger.GatedFilter -func (a *audit) ComposeFrom(events []*eventlogger.Event) (eventlogger.EventType, interface{}, error) { +func (a *audit) ComposeFrom(events []*eventlogger.Event) (eventlogger.EventType, any, error) { const op = "event.(audit).ComposedFrom" if len(events) == 0 { return "", nil, fmt.Errorf("%s: missing events: %w", op, ErrInvalidParameter) diff --git a/internal/observability/event/event_error.go b/internal/observability/event/event_error.go index 5ee479b1b8..8813312dd6 100644 --- a/internal/observability/event/event_error.go +++ b/internal/observability/event/event_error.go @@ -8,13 +8,13 @@ import ( const errorVersion = "v0.1" type err struct { - Error string `json:"error"` - ErrorFields error `json:"error_fields"` - Id Id `json:"id,omitempty"` - Version string `json:"version"` - Op Op `json:"op,omitempty"` - RequestInfo *RequestInfo `json:"request_info,omitempty"` - Info map[string]interface{} `json:"info,omitempty"` + Error string `json:"error"` + ErrorFields error `json:"error_fields"` + Id Id `json:"id,omitempty"` + Version string `json:"version"` + Op Op `json:"op,omitempty"` + RequestInfo *RequestInfo `json:"request_info,omitempty"` + Info map[string]any `json:"info,omitempty"` } func newError(fromOperation Op, e error, opt ...Option) (*err, error) { diff --git a/internal/observability/event/event_error_test.go b/internal/observability/event/event_error_test.go index e6c0f5d0f8..bfd8804381 100644 --- a/internal/observability/event/event_error_test.go +++ b/internal/observability/event/event_error_test.go @@ -59,7 +59,7 @@ func Test_newError(t *testing.T) { Op: Op("valid-all-opts"), Id: "valid-all-opts", RequestInfo: TestRequestInfo(t), - Info: map[string]interface{}{"msg": "hello"}, + Info: map[string]any{"msg": "hello"}, }, }, } diff --git a/internal/observability/event/event_observation.go b/internal/observability/event/event_observation.go index 1ee91041e0..68c11824b0 100644 --- a/internal/observability/event/event_observation.go +++ b/internal/observability/event/event_observation.go @@ -12,13 +12,13 @@ import ( const observationVersion = "v0.1" type observation struct { - Version string `json:"version"` - Op Op `json:"op,omitempty"` - RequestInfo *RequestInfo `json:"request_info,omitempty"` - ID string `json:"-"` - Flush bool `json:"-"` - Header map[string]interface{} `json:"header,omitempty"` - Detail map[string]interface{} `json:"detail,omitempty"` + Version string `json:"version"` + Op Op `json:"op,omitempty"` + RequestInfo *RequestInfo `json:"request_info,omitempty"` + ID string `json:"-"` + Flush bool `json:"-"` + Header map[string]any `json:"header,omitempty"` + Detail map[string]any `json:"detail,omitempty"` } func newObservation(fromOperation Op, opt ...Option) (*observation, error) { @@ -72,13 +72,13 @@ func (i *observation) validate() error { // Flushed/Processed from a collection of gated observation events. The payload // returned is not a Gateable payload intentionally. Note: the receiver is // always nil when this function is called. -func (o *observation) ComposeFrom(events []*eventlogger.Event) (eventlogger.EventType, interface{}, error) { +func (o *observation) ComposeFrom(events []*eventlogger.Event) (eventlogger.EventType, any, error) { const op = "event.(observation).ComposedFrom" if len(events) == 0 { return "", nil, fmt.Errorf("%s: missing events: %w", op, eventlogger.ErrInvalidParameter) } - payload := map[string]interface{}{} + payload := map[string]any{} for i, v := range events { g, ok := v.Payload.(*observation) if !ok { diff --git a/internal/observability/event/event_observation_test.go b/internal/observability/event/event_observation_test.go index 73fa81daac..c1718d1448 100644 --- a/internal/observability/event/event_observation_test.go +++ b/internal/observability/event/event_observation_test.go @@ -13,9 +13,9 @@ func Test_newObservation(t *testing.T) { now := time.Now() - testHeader := []interface{}{"public-id", "public-id", "now", now} + testHeader := []any{"public-id", "public-id", "now", now} - testDetails := []interface{}{"file_name", "tmpfile-name"} + testDetails := []any{"file_name", "tmpfile-name"} tests := []struct { name string @@ -50,8 +50,8 @@ func Test_newObservation(t *testing.T) { }, want: &observation{ ID: "valid-all-opts", - Header: map[string]interface{}{"public-id": "public-id", "now": now}, - Detail: map[string]interface{}{"file_name": "tmpfile-name"}, + Header: map[string]any{"public-id": "public-id", "now": now}, + Detail: map[string]any{"file_name": "tmpfile-name"}, Flush: true, Version: errorVersion, Op: Op("valid-all-opts"), diff --git a/internal/observability/event/event_sys.go b/internal/observability/event/event_sys.go index cfc4d217d7..81a427b8ac 100644 --- a/internal/observability/event/event_sys.go +++ b/internal/observability/event/event_sys.go @@ -4,10 +4,10 @@ package event const sysVersion = "v0.1" type sysEvent struct { - Id Id `json:"-"` - Version string `json:"version"` - Op Op `json:"op,omitempty"` - Data map[string]interface{} `json:"data"` + Id Id `json:"-"` + Version string `json:"version"` + Op Op `json:"op,omitempty"` + Data map[string]any `json:"data"` } // EventType is required for all event types by the eventlogger broker diff --git a/internal/observability/event/eventer.go b/internal/observability/event/eventer.go index 0c7c1944b5..e4c4d8cb79 100644 --- a/internal/observability/event/eventer.go +++ b/internal/observability/event/eventer.go @@ -53,7 +53,7 @@ type flushable interface { // to substitute our testing broker when needed to write tests for things // like event send retrying. type broker interface { - Send(ctx context.Context, t eventlogger.EventType, payload interface{}) (eventlogger.Status, error) + Send(ctx context.Context, t eventlogger.EventType, payload any) (eventlogger.Status, error) Reopen(ctx context.Context) error StopTimeAt(now time.Time) RegisterNode(id eventlogger.NodeID, node eventlogger.Node) error @@ -65,7 +65,7 @@ type broker interface { // gating type queuedEvent struct { ctx context.Context - event interface{} + event any } // Eventer provides a method to send events to pipelines of sinks @@ -77,7 +77,7 @@ type Eventer struct { auditPipelines []pipeline observationPipelines []pipeline errPipelines []pipeline - auditWrapperNodes []interface{} + auditWrapperNodes []any // Gating is used to delay output of events until after we have a chance to // render startup info, similar to what was done for hclog before eventing @@ -246,7 +246,7 @@ func NewEventer(log hclog.Logger, serializationLock *sync.Mutex, serverName stri logger: log, conf: c, broker: b, - auditWrapperNodes: []interface{}{}, + auditWrapperNodes: []any{}, } if !opts.withNow.IsZero() { @@ -920,7 +920,7 @@ func (s *logAdapter) pickType(str string) (Type, string) { } } -func isNil(i interface{}) bool { +func isNil(i any) bool { if i == nil { return true } diff --git a/internal/observability/event/eventer_test.go b/internal/observability/event/eventer_test.go index c0a4b81f90..e1503d7216 100644 --- a/internal/observability/event/eventer_test.go +++ b/internal/observability/event/eventer_test.go @@ -170,8 +170,8 @@ func TestEventer_writeObservation(t *testing.T) { eventer, err := NewEventer(testLogger, testLock, "TestEventer_writeObservation", testSetup.EventerConfig) require.NoError(t, err) - testHeader := map[string]interface{}{"name": "header"} - testDetail := map[string]interface{}{"name": "details"} + testHeader := map[string]any{"name": "header"} + testDetail := map[string]any{"name": "details"} testObservation, err := newObservation("Test_NewEventer", WithHeader(testHeader), WithDetails(testDetail)) require.NoError(t, err) @@ -224,7 +224,7 @@ func TestEventer_writeObservation(t *testing.T) { e, err := NewEventer(testLogger, testLock, "e2e-test", c) require.NoError(err) - m := map[string]interface{}{ + m := map[string]any{ "name": "bar", "list": []string{"1", "2"}, } @@ -1132,12 +1132,12 @@ func Test_logAdapter_Write(t *testing.T) { require.NoErrorf(err, "json: %s", string(b)) if tt.wantErrorEvent != "" { - gotData := gotEvent.Data.(map[string]interface{}) + gotData := gotEvent.Data.(map[string]any) t.Log(tt.name, gotData) assert.Equal(tt.wantErrorEvent, gotData["error"]) } if tt.wantSystemEvent != "" { - gotData := gotEvent.Data.(map[string]interface{})["data"].(map[string]interface{}) + gotData := gotEvent.Data.(map[string]any)["data"].(map[string]any) t.Log(tt.name, gotData) assert.Equal(tt.wantSystemEvent, gotData["msg"]) } diff --git a/internal/observability/event/hclog_event_adapter.go b/internal/observability/event/hclog_event_adapter.go index 3162768cd4..ddd5a25ed1 100644 --- a/internal/observability/event/hclog_event_adapter.go +++ b/internal/observability/event/hclog_event_adapter.go @@ -21,7 +21,7 @@ type HclogLoggerAdapter struct { l *sync.RWMutex level hclog.Level name string - withArgs []interface{} + withArgs []any } // Ensure that we are implementing Logger @@ -47,7 +47,7 @@ func NewHclogLogger(ctx context.Context, e *Eventer, opt ...Option) (hclog.Logge // keys must be strings // vals can be any type, but display is implementation specific // Emit a message and key/value pairs at a provided log level -func (h *HclogLoggerAdapter) Log(level hclog.Level, msg string, args ...interface{}) { +func (h *HclogLoggerAdapter) Log(level hclog.Level, msg string, args ...any) { switch { case h.level == hclog.NoLevel: // If logger is not set to any level, accept it case h.level <= level: // Otherwise if logger is same or more verbose, accept @@ -58,7 +58,7 @@ func (h *HclogLoggerAdapter) Log(level hclog.Level, msg string, args ...interfac } // Emit a message and key/value pairs at the TRACE level -func (h *HclogLoggerAdapter) Trace(msg string, args ...interface{}) { +func (h *HclogLoggerAdapter) Trace(msg string, args ...any) { if h.level > hclog.Trace { return } @@ -66,7 +66,7 @@ func (h *HclogLoggerAdapter) Trace(msg string, args ...interface{}) { } // Emit a message and key/value pairs at the DEBUG level -func (h *HclogLoggerAdapter) Debug(msg string, args ...interface{}) { +func (h *HclogLoggerAdapter) Debug(msg string, args ...any) { if h.level > hclog.Debug { return } @@ -74,7 +74,7 @@ func (h *HclogLoggerAdapter) Debug(msg string, args ...interface{}) { } // Emit a message and key/value pairs at the INFO level -func (h *HclogLoggerAdapter) Info(msg string, args ...interface{}) { +func (h *HclogLoggerAdapter) Info(msg string, args ...any) { if h.level > hclog.Info { return } @@ -82,7 +82,7 @@ func (h *HclogLoggerAdapter) Info(msg string, args ...interface{}) { } // Emit a message and key/value pairs at the WARN level -func (h *HclogLoggerAdapter) Warn(msg string, args ...interface{}) { +func (h *HclogLoggerAdapter) Warn(msg string, args ...any) { if h.level > hclog.Warn { return } @@ -90,17 +90,17 @@ func (h *HclogLoggerAdapter) Warn(msg string, args ...interface{}) { } // Emit a message and key/value pairs at the ERROR level -func (h *HclogLoggerAdapter) Error(msg string, args ...interface{}) { +func (h *HclogLoggerAdapter) Error(msg string, args ...any) { if h.level > hclog.Error { return } h.writeEvent("", msg, args) } -func (h *HclogLoggerAdapter) writeEvent(caller Op, msg string, args []interface{}) { +func (h *HclogLoggerAdapter) writeEvent(caller Op, msg string, args []any) { h.l.RLock() defer h.l.RUnlock() - var allArgs []interface{} + var allArgs []any if len(h.withArgs)+len(args) > 0 { allArgs = append(h.withArgs, args...) } @@ -138,17 +138,17 @@ func (h *HclogLoggerAdapter) IsError() bool { } // ImpliedArgs returns With key/value pairs -func (h *HclogLoggerAdapter) ImpliedArgs() []interface{} { +func (h *HclogLoggerAdapter) ImpliedArgs() []any { return h.withArgs } // Creates a sublogger that will always have the given key/value pairs -func (h *HclogLoggerAdapter) With(args ...interface{}) hclog.Logger { +func (h *HclogLoggerAdapter) With(args ...any) hclog.Logger { h.l.Lock() defer h.l.Unlock() newArgs := args if len(h.withArgs) > 0 { - newArgs = make([]interface{}, len(h.withArgs), len(h.withArgs)+len(args)) + newArgs = make([]any, len(h.withArgs), len(h.withArgs)+len(args)) copy(newArgs, h.withArgs) newArgs = append(newArgs, args...) } @@ -175,9 +175,9 @@ func (h *HclogLoggerAdapter) Name() string { func (h *HclogLoggerAdapter) Named(name string) hclog.Logger { h.l.Lock() defer h.l.Unlock() - var newArgs []interface{} + var newArgs []any if len(h.withArgs) > 0 { - newArgs = make([]interface{}, len(h.withArgs)) + newArgs = make([]any, len(h.withArgs)) copy(newArgs, h.withArgs) } @@ -201,9 +201,9 @@ func (h *HclogLoggerAdapter) Named(name string) hclog.Logger { func (h *HclogLoggerAdapter) ResetNamed(name string) hclog.Logger { h.l.Lock() defer h.l.Unlock() - var newArgs []interface{} + var newArgs []any if len(h.withArgs) > 0 { - newArgs = make([]interface{}, len(h.withArgs)) + newArgs = make([]any, len(h.withArgs)) copy(newArgs, h.withArgs) } return &HclogLoggerAdapter{ diff --git a/internal/observability/event/hclog_formatter_node.go b/internal/observability/event/hclog_formatter_node.go index 480ba0a6a2..21f31cdf23 100644 --- a/internal/observability/event/hclog_formatter_node.go +++ b/internal/observability/event/hclog_formatter_node.go @@ -28,7 +28,7 @@ type hclogFormatterFilter struct { // jsonFormat allows you to specify that the hclog entry should be in JSON // fmt. jsonFormat bool - predicate func(ctx context.Context, i interface{}) (bool, error) + predicate func(ctx context.Context, i any) (bool, error) allow []*filter deny []*filter signer signer @@ -144,19 +144,19 @@ func (f *hclogFormatterFilter) Process(ctx context.Context, e *eventlogger.Event } } - var m map[string]interface{} + var m map[string]any switch string(e.Type) { case string(ErrorType), string(AuditType), string(SystemType): s := structs.New(e.Payload) s.TagName = "json" m = s.Map() case string(ObservationType): - m = e.Payload.(map[string]interface{}) + m = e.Payload.(map[string]any) default: return nil, fmt.Errorf("%s: unknown event type %s", op, e.Type) } - args := make([]interface{}, 0, len(m)) + args := make([]any, 0, len(m)) for k, v := range m { if k == requestInfoField && v == nil { continue @@ -170,7 +170,7 @@ func (f *hclogFormatterFilter) Process(ctx context.Context, e *eventlogger.Event } switch { case valueKind == reflect.Map: - for sk, sv := range v.(map[string]interface{}) { + for sk, sv := range v.(map[string]any) { args = append(args, k+":"+sk, sv) } continue @@ -189,7 +189,7 @@ func (f *hclogFormatterFilter) Process(ctx context.Context, e *eventlogger.Event switch { case k == errorFields && v == nil: continue - case k == infoField && len(v.(map[string]interface{})) == 0: + case k == infoField && len(v.(map[string]any)) == 0: continue case k == wrappedField && v == nil: continue @@ -223,7 +223,7 @@ func (f *hclogFormatterFilter) Process(ctx context.Context, e *eventlogger.Event return e, nil } -func hclogBytes(eventType eventlogger.EventType, jsonFormat bool, args []interface{}) (*bytes.Buffer, error) { +func hclogBytes(eventType eventlogger.EventType, jsonFormat bool, args []any) (*bytes.Buffer, error) { var buf bytes.Buffer logger := hclog.New(&hclog.LoggerOptions{ Output: &buf, diff --git a/internal/observability/event/hclog_formatter_node_test.go b/internal/observability/event/hclog_formatter_node_test.go index ab9ba3104a..306880bce4 100644 --- a/internal/observability/event/hclog_formatter_node_test.go +++ b/internal/observability/event/hclog_formatter_node_test.go @@ -53,7 +53,7 @@ func TestHclogFormatter_Process(t *testing.T) { Id: "1", Version: errorVersion, Op: Op("text"), - Data: map[string]interface{}{ + Data: map[string]any{ "msg": "hello", }, }, @@ -72,7 +72,7 @@ func TestHclogFormatter_Process(t *testing.T) { }, e: &eventlogger.Event{ Type: eventlogger.EventType(ObservationType), - Payload: map[string]interface{}{ + Payload: map[string]any{ "id": "1", "version": observationVersion, "latency-ms": 10, @@ -92,7 +92,7 @@ func TestHclogFormatter_Process(t *testing.T) { }, e: &eventlogger.Event{ Type: eventlogger.EventType(ObservationType), - Payload: map[string]interface{}{ + Payload: map[string]any{ "id": "1", "version": observationVersion, "latency-ms": 10, @@ -161,7 +161,7 @@ func TestHclogFormatter_Process(t *testing.T) { Version: errorVersion, Error: ErrInvalidParameter.Error(), Op: Op("text"), - Info: map[string]interface{}{"name": "alice"}, + Info: map[string]any{"name": "alice"}, }, }, want: []string{ @@ -185,7 +185,7 @@ func TestHclogFormatter_Process(t *testing.T) { Id: "1", Version: errorVersion, Op: Op("match-filter"), - Data: map[string]interface{}{ + Data: map[string]any{ "msg": "hello", }, }, @@ -209,7 +209,7 @@ func TestHclogFormatter_Process(t *testing.T) { Id: "1", Version: errorVersion, Op: Op("doesn't match"), - Data: map[string]interface{}{ + Data: map[string]any{ "msg": "hello", }, }, @@ -267,7 +267,7 @@ func TestHclogFormatter_Process(t *testing.T) { require.NoError(err) b, ok := gotEvent.Format(string(JSONHclogSinkFormat)) require.True(ok) - var rep map[string]interface{} + var rep map[string]any require.NoError(json.Unmarshal(b, &rep)) assert.NotEmpty(rep["serialized"]) assert.NotEmpty(rep["serialized_hmac"]) diff --git a/internal/observability/event/options.go b/internal/observability/event/options.go index 6a8cd4ff76..3bf302774e 100644 --- a/internal/observability/event/options.go +++ b/internal/observability/event/options.go @@ -27,10 +27,10 @@ type Option func(*options) // options = how options are represented type options struct { withId string - withDetails map[string]interface{} - withHeader map[string]interface{} + withDetails map[string]any + withHeader map[string]any withFlush bool - withInfo map[string]interface{} + withInfo map[string]any withRequestInfo *RequestInfo withNow time.Time withRequest *Request @@ -70,7 +70,7 @@ func WithId(id string) Option { // WithDetails allows an optional set of key/value pairs about an observation // event at the detail level and observation events may have multiple "details" -func WithDetails(args ...interface{}) Option { +func WithDetails(args ...any) Option { return func(o *options) { o.withDetails = ConvertArgs(args...) } @@ -78,7 +78,7 @@ func WithDetails(args ...interface{}) Option { // WithHeader allows an optional set of key/value pairs about an event at the // header level and observation events will only have one "header" -func WithHeader(args ...interface{}) Option { +func WithHeader(args ...any) Option { return func(o *options) { o.withHeader = ConvertArgs(args...) } @@ -96,7 +96,7 @@ func WithFlush() Option { // specified after WithInfo(...), then WithInfoMsg(...) will overwrite any // values from WithInfo(...). It's recommend that these two options not be used // together. -func WithInfo(args ...interface{}) Option { +func WithInfo(args ...any) Option { return func(o *options) { o.withInfo = ConvertArgs(args...) } @@ -107,11 +107,11 @@ func WithInfo(args ...interface{}) Option { // WithInfo(...) is specified after WithInfoMsg(...), then WithInfo(...) will // overwrite any values from WithInfo(...). It's recommend that these two // options not be used together. -func WithInfoMsg(msg string, args ...interface{}) Option { +func WithInfoMsg(msg string, args ...any) Option { return func(o *options) { o.withInfo = ConvertArgs(args...) if o.withInfo == nil { - o.withInfo = map[string]interface{}{ + o.withInfo = map[string]any{ msgField: msg, } return diff --git a/internal/observability/event/options_test.go b/internal/observability/event/options_test.go index 43aed98150..4f6cefa9eb 100644 --- a/internal/observability/event/options_test.go +++ b/internal/observability/event/options_test.go @@ -29,7 +29,7 @@ func Test_GetOpts(t *testing.T) { assert := assert.New(t) opts := getOpts(WithDetails("name", "alice")) testOpts := getDefaultOptions() - testOpts.withDetails = map[string]interface{}{ + testOpts.withDetails = map[string]any{ "name": "alice", } assert.Equal(opts, testOpts) @@ -38,7 +38,7 @@ func Test_GetOpts(t *testing.T) { assert := assert.New(t) opts := getOpts(WithHeader("name", "alice")) testOpts := getDefaultOptions() - testOpts.withHeader = map[string]interface{}{ + testOpts.withHeader = map[string]any{ "name": "alice", } assert.Equal(opts, testOpts) @@ -54,22 +54,22 @@ func Test_GetOpts(t *testing.T) { assert := assert.New(t) opts := getOpts(WithInfo("name", "alice")) testOpts := getDefaultOptions() - testOpts.withInfo = map[string]interface{}{"name": "alice"} + testOpts.withInfo = map[string]any{"name": "alice"} assert.Equal(opts, testOpts) opts = getOpts(WithInfoMsg("test"), WithInfo("name", "alice")) - testOpts.withInfo = map[string]interface{}{"name": "alice"} + testOpts.withInfo = map[string]any{"name": "alice"} assert.Equal(opts, testOpts) }) t.Run("WithInfoMsg", func(t *testing.T) { assert := assert.New(t) opts := getOpts(WithInfoMsg("test", "name", "alice")) testOpts := getDefaultOptions() - testOpts.withInfo = map[string]interface{}{msgField: "test", "name": "alice"} + testOpts.withInfo = map[string]any{msgField: "test", "name": "alice"} assert.Equal(opts, testOpts) opts = getOpts(WithInfo("name", "alice"), WithInfoMsg("test", "name", "eve")) - testOpts.withInfo = map[string]interface{}{ + testOpts.withInfo = map[string]any{ "msg": "test", "name": "eve", } diff --git a/internal/observability/event/testing.go b/internal/observability/event/testing.go index 1ee10b096b..105a05bd91 100644 --- a/internal/observability/event/testing.go +++ b/internal/observability/event/testing.go @@ -292,7 +292,7 @@ func (b *testMockBroker) RegisterPipeline(def eventlogger.Pipeline) error { return nil } -func (b *testMockBroker) Send(ctx context.Context, t eventlogger.EventType, payload interface{}) (eventlogger.Status, error) { +func (b *testMockBroker) Send(ctx context.Context, t eventlogger.EventType, payload any) (eventlogger.Status, error) { if b.errorOnSend != nil { return eventlogger.Status{}, b.errorOnSend } diff --git a/internal/oplog/oplog.go b/internal/oplog/oplog.go index 7f2c8c9286..c1b39aa0b6 100644 --- a/internal/oplog/oplog.go +++ b/internal/oplog/oplog.go @@ -177,7 +177,7 @@ func convertToDbwOpts(ctx context.Context, opts *OperationOptions) ([]dbw.Option expr := dbw.ExprValue{ Sql: pbVal.ExprValue.GetSql(), } - args := make([]interface{}, 0, len(pbVal.ExprValue.GetArgs())) + args := make([]any, 0, len(pbVal.ExprValue.GetArgs())) for _, a := range pbVal.ExprValue.GetArgs() { args = append(args, a.AsInterface()) } @@ -200,7 +200,7 @@ func convertToDbwOpts(ctx context.Context, opts *OperationOptions) ([]dbw.Option } if opts.GetWithWhereClause() != "" { sql := opts.GetWithWhereClause() - args := make([]interface{}, 0, len(opts.GetWithWhereClauseArgs())) + args := make([]any, 0, len(opts.GetWithWhereClauseArgs())) for _, a := range opts.GetWithWhereClauseArgs() { args = append(args, a.AsInterface()) } @@ -444,7 +444,7 @@ func (e *Entry) Replay(ctx context.Context, tx *Writer, types *TypeCatalog, tabl // TODO: jimlambrt 12/2021 -> while this will work for // CreateItems(...) it's hardly efficient. We'll need to refactor // oplog quite a bit to support a multi-message operation. - if err := rw.CreateItems(ctx, []interface{}{m.Message}, m.Opts...); err != nil { + if err := rw.CreateItems(ctx, []any{m.Message}, m.Opts...); err != nil { return errors.Wrap(ctx, err, op) } case OpType_OP_TYPE_UPDATE: @@ -459,7 +459,7 @@ func (e *Entry) Replay(ctx context.Context, tx *Writer, types *TypeCatalog, tabl // TODO: jimlambrt 12/2021 -> while this will work for // DeleteItems(...) it's hardly efficient. We'll need to refactor // oplog quite a bit to support a multi-message operation. - if _, err := rw.DeleteItems(ctx, []interface{}{m.Message}, m.Opts...); err != nil { + if _, err := rw.DeleteItems(ctx, []any{m.Message}, m.Opts...); err != nil { return errors.Wrap(ctx, err, op) } default: diff --git a/internal/oplog/oplog_test.go b/internal/oplog/oplog_test.go index e5cd4d3ca2..e2948520f9 100644 --- a/internal/oplog/oplog_test.go +++ b/internal/oplog/oplog_test.go @@ -62,7 +62,7 @@ func Test_BasicOplog(t *testing.T) { entryId := l.Id var foundEntry Entry - err = dbw.New(db).LookupWhere(testCtx, &foundEntry, "id = ?", []interface{}{entryId}) + err = dbw.New(db).LookupWhere(testCtx, &foundEntry, "id = ?", []any{entryId}) require.NoError(err) foundEntry.Cipherer = cipherer err = foundEntry.DecryptData(context.Background()) @@ -408,7 +408,7 @@ func Test_Replay(t *testing.T) { userCreateItems := &oplog_test.TestUser{ Name: "foo-" + testId(t), } - require.NoError(dbw.New(db).CreateItems(context.Background(), []interface{}{userCreateItems})) + require.NoError(dbw.New(db).CreateItems(context.Background(), []any{userCreateItems})) err = newLogEntry.WriteEntryWith(context.Background(), &Writer{tx.DB()}, ticket, &Message{Message: userCreate, TypeName: "user", OpType: OpType_OP_TYPE_CREATE}, @@ -425,7 +425,7 @@ func Test_Replay(t *testing.T) { require.NoError(err) var foundEntry Entry - require.NoError(tx.LookupWhere(testCtx, &foundEntry, "id = ?", []interface{}{newLogEntry.Id})) + require.NoError(tx.LookupWhere(testCtx, &foundEntry, "id = ?", []any{newLogEntry.Id})) foundEntry.Cipherer = cipherer err = foundEntry.DecryptData(context.Background()) require.NoError(err) @@ -436,7 +436,7 @@ func Test_Replay(t *testing.T) { var foundReplayedUser oplog_test.TestUser foundReplayedUser.Table = foundReplayedUser.TableName() + tableSuffix - require.NoError(tx.LookupWhere(testCtx, &foundReplayedUser, "id = ?", []interface{}{userCreate.Id})) + require.NoError(tx.LookupWhere(testCtx, &foundReplayedUser, "id = ?", []any{userCreate.Id})) require.NoError(err) assert.Equal(foundUser.Id, foundReplayedUser.Id) @@ -447,7 +447,7 @@ func Test_Replay(t *testing.T) { assert.Equal(foundReplayedUser.Email, loginName+"@hashicorp.com") foundReplayedUser.Id = 0 - require.NoError(tx.LookupWhere(testCtx, &foundReplayedUser, "id = ?", []interface{}{userCreateItems.Id}, dbw.WithDebug(true))) + require.NoError(tx.LookupWhere(testCtx, &foundReplayedUser, "id = ?", []any{userCreateItems.Id}, dbw.WithDebug(true))) require.NoError(err) }) @@ -495,7 +495,7 @@ func Test_Replay(t *testing.T) { require.NoError(err) var foundEntry2 Entry - err = tx2.LookupWhere(testCtx, &foundEntry2, "id = ?", []interface{}{newLogEntry2.Id}) + err = tx2.LookupWhere(testCtx, &foundEntry2, "id = ?", []any{newLogEntry2.Id}) require.NoError(err) foundEntry2.Cipherer = cipherer err = foundEntry2.DecryptData(context.Background()) @@ -508,11 +508,11 @@ func Test_Replay(t *testing.T) { require.NoError(err) var foundUser2 oplog_test.TestUser - err = tx2.LookupWhere(testCtx, &foundUser2, "id = ?", []interface{}{userCreate2.Id}) + err = tx2.LookupWhere(testCtx, &foundUser2, "id = ?", []any{userCreate2.Id}) assert.ErrorIs(err, dbw.ErrRecordNotFound) var foundReplayedUser2 oplog_test.TestUser - err = tx2.LookupWhere(testCtx, &foundReplayedUser2, "id = ?", []interface{}{userCreate2.Id}) + err = tx2.LookupWhere(testCtx, &foundReplayedUser2, "id = ?", []any{userCreate2.Id}) assert.ErrorIs(err, dbw.ErrRecordNotFound) }) t.Run("replay:deleteitems", func(t *testing.T) { @@ -537,7 +537,7 @@ func Test_Replay(t *testing.T) { deleteUser2 := oplog_test.TestUser{ Id: userCreate2.Id, } - _, err = tx2.DeleteItems(testCtx, []interface{}{&deleteUser2}) + _, err = tx2.DeleteItems(testCtx, []any{&deleteUser2}) require.NoError(err) newLogEntry2, err := NewEntry( @@ -559,7 +559,7 @@ func Test_Replay(t *testing.T) { require.NoError(err) var foundEntry2 Entry - err = tx2.LookupWhere(testCtx, &foundEntry2, "id = ?", []interface{}{newLogEntry2.Id}) + err = tx2.LookupWhere(testCtx, &foundEntry2, "id = ?", []any{newLogEntry2.Id}) require.NoError(err) foundEntry2.Cipherer = cipherer err = foundEntry2.DecryptData(context.Background()) @@ -572,11 +572,11 @@ func Test_Replay(t *testing.T) { require.NoError(err) var foundUser2 oplog_test.TestUser - err = tx2.LookupWhere(testCtx, &foundUser2, "id = ?", []interface{}{userCreate2.Id}) + err = tx2.LookupWhere(testCtx, &foundUser2, "id = ?", []any{userCreate2.Id}) assert.ErrorIs(err, dbw.ErrRecordNotFound) var foundReplayedUser2 oplog_test.TestUser - err = tx2.LookupWhere(testCtx, &foundReplayedUser2, "id = ?", []interface{}{userCreate2.Id}) + err = tx2.LookupWhere(testCtx, &foundReplayedUser2, "id = ?", []any{userCreate2.Id}) assert.ErrorIs(err, dbw.ErrRecordNotFound) }) } @@ -625,7 +625,7 @@ func Test_WriteEntryWith(t *testing.T) { require.NoError(err) var foundEntry Entry - require.NoError(dbw.New(db).LookupWhere(testCtx, &foundEntry, "id = ?", []interface{}{newLogEntry.Id})) + require.NoError(dbw.New(db).LookupWhere(testCtx, &foundEntry, "id = ?", []any{newLogEntry.Id})) require.NoError(err) foundEntry.Cipherer = cipherer types, err := NewTypeCatalog(testCtx, Type{new(oplog_test.TestUser), "user"}) @@ -773,7 +773,7 @@ func TestEntry_WriteEntryWith(t *testing.T) { Opts: []dbw.Option{ dbw.WithOnConflict(&dbw.OnConflict{ Target: dbw.Columns{"name"}, - Action: dbw.SetColumnValues(map[string]interface{}{"name": dbw.Expr("NULL")}), + Action: dbw.SetColumnValues(map[string]any{"name": dbw.Expr("NULL")}), }), }, }, @@ -788,7 +788,7 @@ func TestEntry_WriteEntryWith(t *testing.T) { Opts: []dbw.Option{ dbw.WithOnConflict(&dbw.OnConflict{ Target: dbw.Columns{"name"}, - Action: dbw.SetColumnValues(map[string]interface{}{"name": testId(t)}), + Action: dbw.SetColumnValues(map[string]any{"name": testId(t)}), }), }, }, @@ -869,7 +869,7 @@ func TestEntry_WriteEntryWith(t *testing.T) { } require.NoError(err) var foundEntry Entry - require.NoError(dbw.New(db).LookupWhere(testCtx, &foundEntry, "id = ?", []interface{}{tt.e.Id})) + require.NoError(dbw.New(db).LookupWhere(testCtx, &foundEntry, "id = ?", []any{tt.e.Id})) require.NoError(err) foundEntry.Cipherer = cipherer types, err := NewTypeCatalog(testCtx, Type{new(oplog_test.TestUser), "user"}) @@ -900,7 +900,7 @@ func TestEntry_WriteEntryWith(t *testing.T) { var foundReplayedUser oplog_test.TestUser foundReplayedUser.Table = foundReplayedUser.TableName() + tableSuffix - require.NoError(dbw.New(tt.w.DB).LookupWhere(testCtx, &foundReplayedUser, "id = ?", []interface{}{entryUser.Id})) + require.NoError(dbw.New(tt.w.DB).LookupWhere(testCtx, &foundReplayedUser, "id = ?", []any{entryUser.Id})) require.NoError(err) assert.Equal(foundUser.Id, foundReplayedUser.Id) diff --git a/internal/oplog/options.go b/internal/oplog/options.go index 62809e36de..c8322913c9 100644 --- a/internal/oplog/options.go +++ b/internal/oplog/options.go @@ -17,7 +17,7 @@ func GetOpts(opt ...Option) Options { type Option func(Options) // Options = how options are represented -type Options map[string]interface{} +type Options map[string]any func getDefaultOptions() Options { return Options{ diff --git a/internal/oplog/testing.go b/internal/oplog/testing.go index 1e18fec55b..d43c2a0364 100644 --- a/internal/oplog/testing.go +++ b/internal/oplog/testing.go @@ -66,7 +66,7 @@ func testUser(t testing.TB, db *dbw.DB, name, phoneNumber, email string) *oplog_ func testFindUser(t testing.TB, db *dbw.DB, userId uint32) *oplog_test.TestUser { t.Helper() var foundUser oplog_test.TestUser - require.NoError(t, dbw.New(db).LookupWhere(context.Background(), &foundUser, "id = ?", []interface{}{userId})) + require.NoError(t, dbw.New(db).LookupWhere(context.Background(), &foundUser, "id = ?", []any{userId})) return &foundUser } @@ -139,7 +139,7 @@ where ccu.table_name = ? order by ccu.table_name,pgc.conname ` rw := dbw.New(db) - rows, err := rw.Query(testCtx, constraintSql, []interface{}{tableName}) + rows, err := rw.Query(testCtx, constraintSql, []any{tableName}) require.NoError(err) type result struct { Name string diff --git a/internal/oplog/ticketer.go b/internal/oplog/ticketer.go index 6bb82e09c1..ec5c670862 100644 --- a/internal/oplog/ticketer.go +++ b/internal/oplog/ticketer.go @@ -54,7 +54,7 @@ func (ticketer *DbwTicketer) GetTicket(ctx context.Context, aggregateName string name = aggregateName } ticket := store.Ticket{} - if err := dbw.New(ticketer.tx).LookupWhere(ctx, &ticket, "name = ?", []interface{}{name}); err != nil { + if err := dbw.New(ticketer.tx).LookupWhere(ctx, &ticket, "name = ?", []any{name}); err != nil { if errors.Is(err, dbw.ErrRecordNotFound) { return nil, errors.New(ctx, errors.TicketNotFound, op, "ticket not found") } diff --git a/internal/oplog/type_catalog.go b/internal/oplog/type_catalog.go index 7300ab9feb..8bbd6b5dd5 100644 --- a/internal/oplog/type_catalog.go +++ b/internal/oplog/type_catalog.go @@ -16,7 +16,7 @@ type TypeCatalog map[string]reflect.Type // refactor the type name without breaking the catalog type Type struct { // Interface of the type - Interface interface{} + Interface any // Name for the interface Name string } @@ -37,7 +37,7 @@ func NewTypeCatalog(ctx context.Context, withTypes ...Type) (*TypeCatalog, error } // GetTypeName returns the interface's name from the catalog -func (t *TypeCatalog) GetTypeName(ctx context.Context, i interface{}) (string, error) { +func (t *TypeCatalog) GetTypeName(ctx context.Context, i any) (string, error) { const op = "oplog.(TypeCatalog).GetTypeName" if i == nil { return "", errors.New(ctx, errors.InvalidParameter, op, "nil interface") @@ -55,7 +55,7 @@ func (t *TypeCatalog) GetTypeName(ctx context.Context, i interface{}) (string, e } // Set creates an entry in the catalog for the interface -func (t TypeCatalog) Set(ctx context.Context, i interface{}, typeName string) error { +func (t TypeCatalog) Set(ctx context.Context, i any, typeName string) error { const op = "oplog.(TypeCatalog).Set" if i == nil { return errors.New(ctx, errors.InvalidParameter, op, "nil interface") @@ -71,7 +71,7 @@ func (t TypeCatalog) Set(ctx context.Context, i interface{}, typeName string) er } // Get retrieves the interface via a name -func (t TypeCatalog) Get(ctx context.Context, typeName string) (interface{}, error) { +func (t TypeCatalog) Get(ctx context.Context, typeName string) (any, error) { const op = "oplog.(TypeCatalog).Get" if typeName == "" { return nil, errors.New(ctx, errors.InvalidParameter, op, "missing type name") diff --git a/internal/oplog/writer.go b/internal/oplog/writer.go index 4fe321ea5a..bec8efc2eb 100644 --- a/internal/oplog/writer.go +++ b/internal/oplog/writer.go @@ -22,7 +22,7 @@ func (w *Writer) hasTable(ctx context.Context, tableName string) (bool, error) { } var count int64 rw := dbw.New(w.DB) - rows, err := rw.Query(context.Background(), "select count(*) from information_schema.tables where table_name = ? and table_type = ?", []interface{}{tableName, "BASE TABLE"}) + rows, err := rw.Query(context.Background(), "select count(*) from information_schema.tables where table_name = ? and table_type = ?", []any{tableName, "BASE TABLE"}) if err != nil { return false, errors.Wrap(ctx, err, op) } diff --git a/internal/oplog/writer_test.go b/internal/oplog/writer_test.go index 9c6c3eeb7d..3a0c0527d3 100644 --- a/internal/oplog/writer_test.go +++ b/internal/oplog/writer_test.go @@ -67,7 +67,7 @@ func Test_WriterDelete(t *testing.T) { _, err = dbw.New(w.DB).Delete(testCtx, &user) require.NoError(err) - err = dbw.New(w.DB).LookupWhere(testCtx, &foundUser, "id = ?", []interface{}{user.Id}) + err = dbw.New(w.DB).LookupWhere(testCtx, &foundUser, "id = ?", []any{user.Id}) require.Error(err) assert.ErrorIs(err, dbw.ErrRecordNotFound) }) diff --git a/internal/perms/grants.go b/internal/perms/grants.go index f4817e4952..bfcb5342be 100644 --- a/internal/perms/grants.go +++ b/internal/perms/grants.go @@ -143,7 +143,7 @@ func (g Grant) CanonicalString() string { // MarshalJSON provides a custom marshaller for grants func (g Grant) MarshalJSON() ([]byte, error) { const op = "perms.(Grant).MarshalJSON" - res := make(map[string]interface{}, 4) + res := make(map[string]any, 4) if g.id != "" { res["id"] = g.id } @@ -173,7 +173,7 @@ func (g Grant) MarshalJSON() ([]byte, error) { // when JSON is detected. func (g *Grant) unmarshalJSON(data []byte) error { const op = "perms.(Grant).unmarshalJSON" - raw := make(map[string]interface{}, 4) + raw := make(map[string]any, 4) if err := json.Unmarshal(data, &raw); err != nil { return errors.WrapDeprecated(err, op, errors.WithCode(errors.Decode)) } @@ -195,7 +195,7 @@ func (g *Grant) unmarshalJSON(data []byte) error { } } if rawActions, ok := raw["actions"]; ok { - interfaceActions, ok := rawActions.([]interface{}) + interfaceActions, ok := rawActions.([]any) if !ok { return errors.NewDeprecated(errors.InvalidParameter, op, fmt.Sprintf("unable to interpret %q as array", "actions")) } @@ -215,7 +215,7 @@ func (g *Grant) unmarshalJSON(data []byte) error { } } if rawOutputFields, ok := raw["output_fields"]; ok { - interfaceOutputFields, ok := rawOutputFields.([]interface{}) + interfaceOutputFields, ok := rawOutputFields.([]any) if !ok { return errors.NewDeprecated(errors.InvalidParameter, op, fmt.Sprintf("unable to interpret %q as array", "output_fields")) } diff --git a/internal/plugin/host/repository_plugin.go b/internal/plugin/host/repository_plugin.go index 8babbcc7f9..29bf28ae9c 100644 --- a/internal/plugin/host/repository_plugin.go +++ b/internal/plugin/host/repository_plugin.go @@ -112,7 +112,7 @@ func (r *Repository) LookupPluginByName(ctx context.Context, name string, _ ...O } p := allocPlugin() - if err := r.reader.LookupWhere(ctx, p, "name=?", []interface{}{name}); err != nil { + if err := r.reader.LookupWhere(ctx, p, "name=?", []any{name}); err != nil { if errors.IsNotFoundError(err) { return nil, nil } @@ -134,7 +134,7 @@ func (r *Repository) ListPlugins(ctx context.Context, scopeIds []string, opt ... limit = opts.withLimit } var plugins []*Plugin - err := r.reader.SearchWhere(ctx, &plugins, "scope_id in (?)", []interface{}{scopeIds}, db.WithLimit(limit)) + err := r.reader.SearchWhere(ctx, &plugins, "scope_id in (?)", []any{scopeIds}, db.WithLimit(limit)) if err != nil { return nil, errors.Wrap(ctx, err, op) } diff --git a/internal/scheduler/job/additional_verification_test.go b/internal/scheduler/job/additional_verification_test.go index d261ccc021..76e7bf377a 100644 --- a/internal/scheduler/job/additional_verification_test.go +++ b/internal/scheduler/job/additional_verification_test.go @@ -100,7 +100,7 @@ func TestPlugin(t *testing.T) { conn, _ := db.TestSetup(t, "postgres") rw := db.New(conn) - rows, err := rw.Query(context.Background(), upsertJobQuery, []interface{}{ + rows, err := rw.Query(context.Background(), upsertJobQuery, []any{ sql.Named("plugin_id", defaultPluginId), sql.Named("name", "same-job-name"), sql.Named("description", "description"), @@ -119,7 +119,7 @@ func TestPlugin(t *testing.T) { require.Equal(1, numRows) // Calling upsertJob with same name and pluginId should not insert a new job - rows, err = rw.Query(context.Background(), upsertJobQuery, []interface{}{ + rows, err = rw.Query(context.Background(), upsertJobQuery, []any{ sql.Named("plugin_id", defaultPluginId), sql.Named("name", "same-job-name"), sql.Named("description", "description"), @@ -140,12 +140,12 @@ func TestPlugin(t *testing.T) { // Create test plugin id testPluginId := "pi_test1234" - numRows, err = rw.Exec(context.Background(), "insert into plugin(public_id, scope_id) values (?, 'global')", []interface{}{testPluginId}) + numRows, err = rw.Exec(context.Background(), "insert into plugin(public_id, scope_id) values (?, 'global')", []any{testPluginId}) require.NoError(err) assert.Equal(1, numRows) // Calling upsertJob with the same name and different pluginId should create a new job - rows, err = rw.Query(context.Background(), upsertJobQuery, []interface{}{ + rows, err = rw.Query(context.Background(), upsertJobQuery, []any{ sql.Named("plugin_id", testPluginId), sql.Named("name", "same-job-name"), sql.Named("description", "description"), @@ -172,12 +172,12 @@ func TestPlugin(t *testing.T) { // Create test plugin id testPluginId := "pi_test1234" - numRows, err := rw.Exec(context.Background(), "insert into plugin(public_id, scope_id) values (?, 'global')", []interface{}{testPluginId}) + numRows, err := rw.Exec(context.Background(), "insert into plugin(public_id, scope_id) values (?, 'global')", []any{testPluginId}) assert.NoError(err) assert.Equal(1, numRows) newPluginId := "pi_newtest1234" - numUpdated, err := rw.Exec(context.Background(), "update plugin set public_id = ? where public_id = ?", []interface{}{newPluginId, testPluginId}) + numUpdated, err := rw.Exec(context.Background(), "update plugin set public_id = ? where public_id = ?", []any{newPluginId, testPluginId}) require.Error(err) assert.Equal("db.Exec: immutable column: plugin.public_id: integrity violation: error #1003", err.Error()) assert.Equal(0, numUpdated) @@ -188,18 +188,18 @@ func TestPlugin(t *testing.T) { conn, _ := db.TestSetup(t, "postgres") rw := db.New(conn) - numDeleted, err := rw.Exec(context.Background(), "delete from plugin where public_id = ?", []interface{}{defaultPluginId}) + numDeleted, err := rw.Exec(context.Background(), "delete from plugin where public_id = ?", []any{defaultPluginId}) require.Error(err) assert.Equal("db.Exec: deletion of system plugin not allowed: integrity violation: error #1104", err.Error()) assert.Equal(0, numDeleted) // Create test plugin id testPluginId := "pi_test1234" - numRows, err := rw.Exec(context.Background(), "insert into plugin(public_id, scope_id) values (?, 'global')", []interface{}{testPluginId}) + numRows, err := rw.Exec(context.Background(), "insert into plugin(public_id, scope_id) values (?, 'global')", []any{testPluginId}) assert.NoError(err) assert.Equal(1, numRows) - numDeleted, err = rw.Exec(context.Background(), "delete from plugin where public_id = ?", []interface{}{testPluginId}) + numDeleted, err = rw.Exec(context.Background(), "delete from plugin where public_id = ?", []any{testPluginId}) assert.NoError(err) assert.Equal(1, numDeleted) }) diff --git a/internal/scheduler/job/repository_job.go b/internal/scheduler/job/repository_job.go index 74e6da8795..664a272d5e 100644 --- a/internal/scheduler/job/repository_job.go +++ b/internal/scheduler/job/repository_job.go @@ -35,7 +35,7 @@ func (r *Repository) UpsertJob(ctx context.Context, name, description string, op j := allocJob() _, err := r.writer.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{}, func(r db.Reader, w db.Writer) error { - rows, err := r.Query(ctx, upsertJobQuery, []interface{}{ + rows, err := r.Query(ctx, upsertJobQuery, []any{ sql.Named("plugin_id", defaultId), sql.Named("name", name), sql.Named("description", description), @@ -88,7 +88,7 @@ func (r *Repository) UpdateJobNextRunInAtLeast(ctx context.Context, name string, j := allocJob() _, err := r.writer.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{}, func(r db.Reader, w db.Writer) error { - rows, err := w.Query(ctx, setNextScheduledRunIfSoonerQuery, []interface{}{int(nextRunInAtLeast.Round(time.Second).Seconds()), defaultPluginId, name}) + rows, err := w.Query(ctx, setNextScheduledRunIfSoonerQuery, []any{int(nextRunInAtLeast.Round(time.Second).Seconds()), defaultPluginId, name}) if err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg( fmt.Sprintf("failed to set next scheduled run time for job %v", name))) @@ -131,7 +131,7 @@ func (r *Repository) LookupJob(ctx context.Context, name string, _ ...Option) (* } j := allocJob() - if err := r.reader.LookupWhere(ctx, j, "name = ?", []interface{}{name}); err != nil { + if err := r.reader.LookupWhere(ctx, j, "name = ?", []any{name}); err != nil { if errors.IsNotFoundError(err) { return nil, nil } @@ -151,7 +151,7 @@ func (r *Repository) ListJobs(ctx context.Context, opt ...Option) ([]*Job, error // non-zero signals an override of the default limit for the repo. limit = opts.withLimit } - var args []interface{} + var args []any var where []string if opts.withName != "" { where, args = append(where, "name = ?"), append(args, opts.withName) @@ -179,7 +179,7 @@ func (r *Repository) deleteJob(ctx context.Context, name string, _ ...Option) (i _, err := r.writer.DoTx( ctx, db.StdRetryCnt, db.ExpBackoff{}, func(_ db.Reader, w db.Writer) (err error) { - rowsDeleted, err = w.Exec(ctx, deleteJobByName, []interface{}{name}) + rowsDeleted, err = w.Exec(ctx, deleteJobByName, []any{name}) if err != nil { return errors.Wrap(ctx, err, op) } diff --git a/internal/scheduler/job/repository_run.go b/internal/scheduler/job/repository_run.go index 17962bd27d..2f46f0f5b1 100644 --- a/internal/scheduler/job/repository_run.go +++ b/internal/scheduler/job/repository_run.go @@ -36,7 +36,7 @@ func (r *Repository) RunJobs(ctx context.Context, serverId string, opt ...Option var runs []*Run _, err := r.writer.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{}, func(r db.Reader, w db.Writer) error { - rows, err := w.Query(ctx, query, []interface{}{serverId}) + rows, err := w.Query(ctx, query, []any{serverId}) if err != nil { return errors.Wrap(ctx, err, op) } @@ -75,7 +75,7 @@ func (r *Repository) UpdateProgress(ctx context.Context, runId string, completed run.PrivateId = runId _, err := r.writer.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{}, func(r db.Reader, w db.Writer) error { - rows, err := w.Query(ctx, updateProgressQuery, []interface{}{completed, total, runId}) + rows, err := w.Query(ctx, updateProgressQuery, []any{completed, total, runId}) if err != nil { return errors.Wrap(ctx, err, op) } @@ -139,7 +139,7 @@ func (r *Repository) CompleteRun(ctx context.Context, runId string, nextRunIn ti // persisted by the scheduler's monitor jobs loop. // Add an on update sql trigger to protect the job_run table, once progress // values are used in the critical path. - rows, err := w.Query(ctx, completeRunQuery, []interface{}{completed, total, runId}) + rows, err := w.Query(ctx, completeRunQuery, []any{completed, total, runId}) if err != nil { return errors.Wrap(ctx, err, op) } @@ -168,7 +168,7 @@ func (r *Repository) CompleteRun(ctx context.Context, runId string, nextRunIn ti return errors.New(ctx, errors.InvalidJobRunState, op, fmt.Sprintf("job run was in a final run state: %v", run.Status), errors.WithoutEvent()) } - rows1, err := w.Query(ctx, setNextScheduledRunQuery, []interface{}{int(nextRunIn.Round(time.Second).Seconds()), run.JobPluginId, run.JobName}) + rows1, err := w.Query(ctx, setNextScheduledRunQuery, []any{int(nextRunIn.Round(time.Second).Seconds()), run.JobPluginId, run.JobName}) if err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed to set next scheduled run time for job: %s", run.JobName))) } @@ -219,7 +219,7 @@ func (r *Repository) FailRun(ctx context.Context, runId string, completed, total // persisted by the scheduler's monitor jobs loop. // Add an on update sql trigger to protect the job_run table, once progress // values are used in the critical path. - rows, err := w.Query(ctx, failRunQuery, []interface{}{completed, total, runId}) + rows, err := w.Query(ctx, failRunQuery, []any{completed, total, runId}) if err != nil { return errors.Wrap(ctx, err, op) } @@ -272,7 +272,7 @@ func (r *Repository) InterruptRuns(ctx context.Context, interruptThreshold time. opts := getOpts(opt...) // interruptThreshold is seconds in past so * -1 - args := []interface{}{-1 * int(interruptThreshold.Round(time.Second).Seconds())} + args := []any{-1 * int(interruptThreshold.Round(time.Second).Seconds())} var whereControllerId string if opts.withControllerId != "" { whereControllerId = "and controller_id = ?" diff --git a/internal/scheduler/job/testing.go b/internal/scheduler/job/testing.go index 698790e71d..90045b790b 100644 --- a/internal/scheduler/job/testing.go +++ b/internal/scheduler/job/testing.go @@ -45,7 +45,7 @@ func testRun(conn *db.DB, pluginId, name, cId string) (*Run, error) { rw := db.New(conn) run := allocRun() ctx := context.Background() - rows, err := rw.Query(ctx, query, []interface{}{pluginId, name, cId}) + rows, err := rw.Query(ctx, query, []any{pluginId, name, cId}) if err != nil { return nil, err } @@ -73,7 +73,7 @@ func testRunWithUpdateTime(conn *db.DB, pluginId, name, cId string, updateTime t rw := db.New(conn) run := allocRun() ctx := context.Background() - rows, err := rw.Query(ctx, query, []interface{}{pluginId, name, cId, updateTime}) + rows, err := rw.Query(ctx, query, []any{pluginId, name, cId, updateTime}) if err != nil { return nil, err } diff --git a/internal/scheduler/job/testing_test.go b/internal/scheduler/job/testing_test.go index 4abd3f74ac..f7ba7f590a 100644 --- a/internal/scheduler/job/testing_test.go +++ b/internal/scheduler/job/testing_test.go @@ -23,7 +23,7 @@ func Test_TestJob(t *testing.T) { rw := db.New(conn) var got Job - err := rw.LookupWhere(context.Background(), &got, "name = ?", []interface{}{job.Name}) + err := rw.LookupWhere(context.Background(), &got, "name = ?", []any{job.Name}) require.NoError(err) assert.Equal("testJob", got.Name) assert.Equal("testDescription", got.Description) @@ -34,7 +34,7 @@ func Test_TestJob(t *testing.T) { require.NotNil(job1) var got1 Job - err = rw.LookupWhere(context.Background(), &got1, "name = ?", []interface{}{job1.Name}) + err = rw.LookupWhere(context.Background(), &got1, "name = ?", []any{job1.Name}) require.NoError(err) assert.Equal("testJob1", got1.Name) assert.Equal("testDescription1", got1.Description) @@ -66,7 +66,7 @@ func Test_TestRun(t *testing.T) { rw := db.New(conn) var got Run - err = rw.LookupWhere(context.Background(), &got, "private_id = ?", []interface{}{run.PrivateId}) + err = rw.LookupWhere(context.Background(), &got, "private_id = ?", []any{run.PrivateId}) require.NoError(err) assert.Equal(server.PrivateId, got.ControllerId) assert.Equal(job.Name, got.JobName) diff --git a/internal/scheduler/scheduler.go b/internal/scheduler/scheduler.go index 4c37442287..049f45744c 100644 --- a/internal/scheduler/scheduler.go +++ b/internal/scheduler/scheduler.go @@ -300,7 +300,7 @@ func (s *Scheduler) monitorJobs(ctx context.Context) { case <-timer.C: // Update progress of all running jobs - s.runningJobs.Range(func(_, v interface{}) bool { + s.runningJobs.Range(func(_, v any) bool { err := s.updateRunningJobProgress(ctx, v.(*runningJob)) if err != nil { event.WriteError(ctx, op, err, event.WithInfoMsg("error updating job progress")) diff --git a/internal/scheduler/scheduler_test.go b/internal/scheduler/scheduler_test.go index ad2da12e08..8e4aad4789 100644 --- a/internal/scheduler/scheduler_test.go +++ b/internal/scheduler/scheduler_test.go @@ -247,7 +247,7 @@ func TestScheduler_RegisterJob(t *testing.T) { // Verify job has been persisted var dbJob job.Job - err = rw.LookupWhere(context.Background(), &dbJob, "name = ?", []interface{}{tt.job.Name()}) + err = rw.LookupWhere(context.Background(), &dbJob, "name = ?", []any{tt.job.Name()}) require.NoError(err) require.NotNil(dbJob) assert.Equal(tt.job.Name(), dbJob.Name) @@ -344,14 +344,14 @@ func TestScheduler_UpdateJobNextRunInAtLeast(t *testing.T) { // get job from repo var dbJob job.Job - err = rw.LookupWhere(context.Background(), &dbJob, "name = ?", []interface{}{tj.name}) + err = rw.LookupWhere(context.Background(), &dbJob, "name = ?", []any{tj.name}) require.NoError(err) previousNextRun := dbJob.NextScheduledRun.AsTime() err = sched.UpdateJobNextRunInAtLeast(context.Background(), tj.name, time.Hour) require.NoError(err) - err = rw.LookupWhere(context.Background(), &dbJob, "name = ?", []interface{}{tj.name}) + err = rw.LookupWhere(context.Background(), &dbJob, "name = ?", []any{tj.name}) require.NoError(err) // Verify job run time in repo is at least 1 hour before than the previous run time assert.Equal(previousNextRun.Add(-1*time.Hour).Round(time.Minute), dbJob.NextScheduledRun.AsTime().Round(time.Minute)) @@ -369,14 +369,14 @@ func TestScheduler_UpdateJobNextRunInAtLeast(t *testing.T) { // get job from repo var dbJob job.Job - err = rw.LookupWhere(context.Background(), &dbJob, "name = ?", []interface{}{tj.name}) + err = rw.LookupWhere(context.Background(), &dbJob, "name = ?", []any{tj.name}) require.NoError(err) previousNextRun := dbJob.NextScheduledRun.AsTime() err = sched.UpdateJobNextRunInAtLeast(context.Background(), tj.name, 4*time.Hour) require.NoError(err) - err = rw.LookupWhere(context.Background(), &dbJob, "name = ?", []interface{}{tj.name}) + err = rw.LookupWhere(context.Background(), &dbJob, "name = ?", []any{tj.name}) require.NoError(err) // Job should not have updated next run time, since its later than the already scheduled time assert.Equal(previousNextRun, dbJob.NextScheduledRun.AsTime()) @@ -384,7 +384,7 @@ func TestScheduler_UpdateJobNextRunInAtLeast(t *testing.T) { err = sched.UpdateJobNextRunInAtLeast(context.Background(), tj.name, time.Hour) require.NoError(err) - err = rw.LookupWhere(context.Background(), &dbJob, "name = ?", []interface{}{tj.name}) + err = rw.LookupWhere(context.Background(), &dbJob, "name = ?", []any{tj.name}) require.NoError(err) // Verify job run time in repo is at least 1 hour before than the previous run time assert.Equal(previousNextRun.Add(-1*time.Hour).Round(time.Minute), dbJob.NextScheduledRun.AsTime().Round(time.Minute)) diff --git a/internal/scheduler/testing.go b/internal/scheduler/testing.go index e8a9ff9752..e4067b46e3 100644 --- a/internal/scheduler/testing.go +++ b/internal/scheduler/testing.go @@ -98,7 +98,7 @@ func (j testJob) Description() string { func mapLen(sm *sync.Map) int { count := 0 - sm.Range(func(key, value interface{}) bool { + sm.Range(func(key, value any) bool { count++ return true }) diff --git a/internal/server/job/jobs.go b/internal/server/job/jobs.go index 50d78a3a99..a171b5475a 100644 --- a/internal/server/job/jobs.go +++ b/internal/server/job/jobs.go @@ -38,7 +38,7 @@ func RegisterJobs(ctx context.Context, scheduler *scheduler.Scheduler, r db.Read return nil } -func isNil(i interface{}) bool { +func isNil(i any) bool { if i == nil { return true } diff --git a/internal/server/repository.go b/internal/server/repository.go index a7df5afff0..bd85cbda86 100644 --- a/internal/server/repository.go +++ b/internal/server/repository.go @@ -57,7 +57,7 @@ func NewRepository(r db.Reader, w db.Writer, kms *kms.Kms, opt ...Option) (*Repo }, nil } -func isNil(i interface{}) bool { +func isNil(i any) bool { if i == nil { return true } diff --git a/internal/server/repository_controller.go b/internal/server/repository_controller.go index 3cc5b45c99..9f090edb3e 100644 --- a/internal/server/repository_controller.go +++ b/internal/server/repository_controller.go @@ -33,7 +33,7 @@ func (r *Repository) listControllersWithReader(ctx context.Context, reader db.Re ctx, &controllers, where, - []interface{}{}, + []any{}, db.WithLimit(-1), ); err != nil { return nil, errors.Wrap(ctx, err, "workers.listControllersWithReader") @@ -58,7 +58,7 @@ func (r *Repository) UpsertController(ctx context.Context, controller *store.Con var err error onConflict := &db.OnConflict{ Target: db.Columns{"private_id"}, - Action: append(db.SetColumns([]string{"description", "address"}), db.SetColumnValues(map[string]interface{}{"update_time": "now()"})...), + Action: append(db.SetColumns([]string{"description", "address"}), db.SetColumnValues(map[string]any{"update_time": "now()"})...), } err = w.Create(ctx, controller, db.WithOnConflict(onConflict), db.WithReturnRowsAffected(&rowsUpdated)) if err != nil { diff --git a/internal/server/repository_nonce.go b/internal/server/repository_nonce.go index 9ba1335f0e..0aa88faa3f 100644 --- a/internal/server/repository_nonce.go +++ b/internal/server/repository_nonce.go @@ -67,7 +67,7 @@ func (r *Repository) CleanupNonces(ctx context.Context, opt ...Option) (int, err // ListNonces lists nonces. Used only for tests at the moment. func (r *Repository) ListNonces(ctx context.Context, purpose string, opt ...Option) ([]*Nonce, error) { var nonces []*Nonce - if err := r.reader.SearchWhere(ctx, &nonces, "purpose = ?", []interface{}{purpose}, db.WithLimit(-1)); err != nil { + if err := r.reader.SearchWhere(ctx, &nonces, "purpose = ?", []any{purpose}, db.WithLimit(-1)); err != nil { return nil, errors.Wrap(ctx, err, "server.ListNonces") } return nonces, nil diff --git a/internal/server/repository_worker.go b/internal/server/repository_worker.go index 2c73f728ff..5b51d79e0d 100644 --- a/internal/server/repository_worker.go +++ b/internal/server/repository_worker.go @@ -84,7 +84,7 @@ func lookupWorkerByName(ctx context.Context, reader db.Reader, name string) (*Wo } wAgg := &workerAggregate{} - err := reader.LookupWhere(ctx, &wAgg, "name = ?", []interface{}{name}) + err := reader.LookupWhere(ctx, &wAgg, "name = ?", []any{name}) if err != nil { if errors.IsNotFoundError(err) { return nil, nil @@ -179,7 +179,7 @@ func (r *Repository) ListWorkers(ctx context.Context, scopeIds []string, opt ... } var where []string - var whereArgs []interface{} + var whereArgs []any if liveness > 0 { where = append(where, fmt.Sprintf("last_status_time > now() - interval '%d seconds'", uint32(liveness.Seconds()))) } @@ -319,7 +319,7 @@ func (r *Repository) UpsertWorkerStatus(ctx context.Context, worker *Worker, opt workerCreateConflict := &db.OnConflict{ Target: db.Columns{"public_id"}, Action: append(db.SetColumns([]string{"address", "release_version", "operational_state"}), - db.SetColumnValues(map[string]interface{}{"last_status_time": "now()"})...), + db.SetColumnValues(map[string]any{"last_status_time": "now()"})...), } var withRowsAffected int64 err := w.Create(ctx, workerClone, db.WithOnConflict(workerCreateConflict), db.WithReturnRowsAffected(&withRowsAffected), @@ -381,7 +381,7 @@ func setWorkerTags(ctx context.Context, w db.Writer, id string, ts TagSource, ta case isNil(w): return errors.New(ctx, errors.InvalidParameter, op, "db.Writer is nil") } - _, err := w.Exec(ctx, deleteTagsByWorkerIdSql, []interface{}{ts.String(), id}) + _, err := w.Exec(ctx, deleteTagsByWorkerIdSql, []any{ts.String(), id}) if err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("couldn't delete existing tags for worker %q", id))) } @@ -391,7 +391,7 @@ func setWorkerTags(ctx context.Context, w db.Writer, id string, ts TagSource, ta // Otherwise, go through and stage each tuple for insertion // below. if len(tags) > 0 { - uTags := make([]interface{}, 0, len(tags)) + uTags := make([]any, 0, len(tags)) for _, v := range tags { if v == nil { return errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("found nil tag value for worker %s", id)) @@ -444,7 +444,7 @@ func (r *Repository) UpdateWorker(ctx context.Context, worker *Worker, version u var dbMask, nullFields []string dbMask, nullFields = dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ nameField: worker.Name, descField: worker.Description, }, @@ -722,7 +722,7 @@ func (r *Repository) DeleteWorkerTags(ctx context.Context, workerId string, work } rowsDeleted := 0 - deleteTags := make([]interface{}, 0, len(tags)) + deleteTags := make([]any, 0, len(tags)) for _, t := range tags { if t == nil { return db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "found nil tag value in input") diff --git a/internal/server/repository_workerauth.go b/internal/server/repository_workerauth.go index 5c1bf32e66..0443a779ad 100644 --- a/internal/server/repository_workerauth.go +++ b/internal/server/repository_workerauth.go @@ -377,7 +377,7 @@ func (r *WorkerAuthRepositoryStorage) loadNodeInformation(ctx context.Context, n } query := getWorkerAuthsByWorkerKeyIdQuery - rows, err := r.reader.Query(ctx, query, []interface{}{sql.Named("worker_key_identifier", node.Id)}) + rows, err := r.reader.Query(ctx, query, []any{sql.Named("worker_key_identifier", node.Id)}) if err != nil { return errors.Wrap(ctx, err, op) } @@ -503,7 +503,7 @@ func (r *WorkerAuthRepositoryStorage) findCertBundles(ctx context.Context, worke } var bundles []*WorkerCertBundle - err := r.reader.SearchWhere(ctx, &bundles, "worker_key_identifier = ?", []interface{}{workerKeyId}, db.WithLimit(-1)) + err := r.reader.SearchWhere(ctx, &bundles, "worker_key_identifier = ?", []any{workerKeyId}, db.WithLimit(-1)) if err != nil { return nil, errors.Wrap(ctx, err, op) } @@ -553,7 +553,7 @@ func (r *WorkerAuthRepositoryStorage) loadRootCertificates(ctx context.Context, rootCertificate := allocRootCertificate() rootCert := &types.RootCertificate{} - if err := r.reader.SearchWhere(ctx, &rootCertificate, "state = ?", []interface{}{c}, db.WithLimit(-1)); err != nil { + if err := r.reader.SearchWhere(ctx, &rootCertificate, "state = ?", []any{c}, db.WithLimit(-1)); err != nil { return errors.Wrap(ctx, err, op) } @@ -635,11 +635,11 @@ func (r *WorkerAuthRepositoryStorage) removeNodeInformation(ctx context.Context, db.ExpBackoff{}, func(reader db.Reader, w db.Writer) error { var err error - _, err = w.Exec(ctx, deleteWorkerAuthQuery, []interface{}{sql.Named("worker_key_identifier", msg.Id)}) + _, err = w.Exec(ctx, deleteWorkerAuthQuery, []any{sql.Named("worker_key_identifier", msg.Id)}) if err != nil { return errors.Wrap(ctx, err, op) } - _, err = w.Exec(ctx, deleteWorkerCertBundlesQuery, []interface{}{sql.Named("worker_key_identifier", msg.Id)}) + _, err = w.Exec(ctx, deleteWorkerCertBundlesQuery, []any{sql.Named("worker_key_identifier", msg.Id)}) if err != nil { return errors.Wrap(ctx, err, op, errors.WithMsg("unable to delete workerAuth")) } @@ -757,7 +757,7 @@ func (r *WorkerAuthRepositoryStorage) removeRootCertificateWithWriter(ctx contex return errors.New(ctx, errors.InvalidParameter, op, "missing writer") } - rows, err := writer.Exec(ctx, deleteRootCertificateQuery, []interface{}{ + rows, err := writer.Exec(ctx, deleteRootCertificateQuery, []any{ sql.Named("state", id), }) if err != nil { @@ -799,7 +799,7 @@ func (r *WorkerAuthRepositoryStorage) listNodeInformation(ctx context.Context) ( var where string var nodeAuths []*WorkerAuth - err := r.reader.SearchWhere(ctx, &nodeAuths, where, []interface{}{}, db.WithLimit(-1)) + err := r.reader.SearchWhere(ctx, &nodeAuths, where, []any{}, db.WithLimit(-1)) if err != nil { return nil, errors.Wrap(ctx, err, op) } @@ -817,7 +817,7 @@ func (r *WorkerAuthRepositoryStorage) listRootCertificates(ctx context.Context) var where string var rootCertificates []*RootCertificate - err := r.reader.SearchWhere(ctx, &rootCertificates, where, []interface{}{}, db.WithLimit(-1)) + err := r.reader.SearchWhere(ctx, &rootCertificates, where, []any{}, db.WithLimit(-1)) if err != nil { return nil, errors.Wrap(ctx, err, op) } @@ -836,7 +836,7 @@ func (r *WorkerAuthRepositoryStorage) listCertificateAuthority(ctx context.Conte var where string var rootCertificates []*CertificateAuthority - err := r.reader.SearchWhere(ctx, &rootCertificates, where, []interface{}{}, db.WithLimit(-1)) + err := r.reader.SearchWhere(ctx, &rootCertificates, where, []any{}, db.WithLimit(-1)) if err != nil { return nil, errors.Wrap(ctx, err, op) } @@ -945,7 +945,7 @@ func (r *WorkerAuthRepositoryStorage) FindWorkerAuthByWorkerId(ctx context.Conte } var workerAuths []*WorkerAuth - if err := r.reader.SearchWhere(ctx, &workerAuths, "worker_id = ?", []interface{}{workerId}); err != nil { + if err := r.reader.SearchWhere(ctx, &workerAuths, "worker_id = ?", []any{workerId}); err != nil { return nil, errors.Wrap(ctx, err, op) } diff --git a/internal/server/testing.go b/internal/server/testing.go index a3c347661e..e14c45bd5c 100644 --- a/internal/server/testing.go +++ b/internal/server/testing.go @@ -125,7 +125,7 @@ func TestKmsWorker(t *testing.T, conn *db.DB, wrapper wrapping.Wrapper, opt ...O require.Equal(t, "kms", wrk.Type) if len(opts.withWorkerTags) > 0 { - var tags []interface{} + var tags []any for _, t := range opts.withWorkerTags { tags = append(tags, &store.WorkerTag{ WorkerId: wrk.GetPublicId(), @@ -164,7 +164,7 @@ func TestPkiWorker(t *testing.T, conn *db.DB, wrapper wrapping.Wrapper, opt ...O require.NotNil(t, wrk) if len(opts.withWorkerTags) > 0 { - var tags []interface{} + var tags []any for _, t := range opts.withWorkerTags { tags = append(tags, &store.WorkerTag{ WorkerId: wrk.GetPublicId(), diff --git a/internal/session/connection.go b/internal/session/connection.go index 07f810911c..95f63a31f2 100644 --- a/internal/session/connection.go +++ b/internal/session/connection.go @@ -78,7 +78,7 @@ func AllocConnection() Connection { } // Clone creates a clone of the Connection. -func (c *Connection) Clone() interface{} { +func (c *Connection) Clone() any { clone := &Connection{ PublicId: c.PublicId, SessionId: c.SessionId, diff --git a/internal/session/connection_state.go b/internal/session/connection_state.go index 7285d87e28..33cc5de541 100644 --- a/internal/session/connection_state.go +++ b/internal/session/connection_state.go @@ -98,7 +98,7 @@ func allocConnectionState() ConnectionState { } // Clone creates a clone of the State -func (s *ConnectionState) Clone() interface{} { +func (s *ConnectionState) Clone() any { clone := &ConnectionState{ ConnectionId: s.ConnectionId, Status: s.Status, diff --git a/internal/session/connection_state_test.go b/internal/session/connection_state_test.go index 6250abcd29..3eb6761421 100644 --- a/internal/session/connection_state_test.go +++ b/internal/session/connection_state_test.go @@ -126,7 +126,7 @@ func TestConnectionState_Delete(t *testing.T) { assert, require := assert.New(t), require.New(t) var initialState ConnectionState - err := rw.LookupWhere(context.Background(), &initialState, "connection_id = ? and state = ?", []interface{}{tt.state.ConnectionId, tt.state.Status}) + err := rw.LookupWhere(context.Background(), &initialState, "connection_id = ? and state = ?", []any{tt.state.ConnectionId, tt.state.Status}) require.NoError(err) deleteState := allocConnectionState() @@ -148,7 +148,7 @@ func TestConnectionState_Delete(t *testing.T) { } assert.Equal(tt.wantRowsDeleted, deletedRows) foundState := allocConnectionState() - err = rw.LookupWhere(context.Background(), &foundState, "connection_id = ? and start_time = ?", []interface{}{tt.state.ConnectionId, initialState.StartTime}) + err = rw.LookupWhere(context.Background(), &foundState, "connection_id = ? and start_time = ?", []any{tt.state.ConnectionId, initialState.StartTime}) require.Error(err) assert.True(errors.IsNotFoundError(err)) }) diff --git a/internal/session/immutable_fields_test.go b/internal/session/immutable_fields_test.go index 2338ebedd4..3d9fbfd484 100644 --- a/internal/session/immutable_fields_test.go +++ b/internal/session/immutable_fields_test.go @@ -102,7 +102,7 @@ func TestState_ImmutableFields(t *testing.T) { state := TestState(t, conn, session.PublicId, StatusActive) var new State - err := rw.LookupWhere(context.Background(), &new, "session_id = ? and state = ?", []interface{}{state.SessionId, state.Status}) + err := rw.LookupWhere(context.Background(), &new, "session_id = ? and state = ?", []any{state.SessionId, state.Status}) require.NoError(t, err) tests := []struct { @@ -152,7 +152,7 @@ func TestState_ImmutableFields(t *testing.T) { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) orig := new.Clone() - err := rw.LookupWhere(context.Background(), orig, "session_id = ? and start_time = ?", []interface{}{new.SessionId, new.StartTime}) + err := rw.LookupWhere(context.Background(), orig, "session_id = ? and start_time = ?", []any{new.SessionId, new.StartTime}) require.NoError(err) rowsUpdated, err := rw.Update(context.Background(), tt.update, tt.fieldMask, nil, db.WithSkipVetForWrite(true)) @@ -160,7 +160,7 @@ func TestState_ImmutableFields(t *testing.T) { assert.Equal(0, rowsUpdated) after := new.Clone() - err = rw.LookupWhere(context.Background(), after, "session_id = ? and start_time = ?", []interface{}{new.SessionId, new.StartTime}) + err = rw.LookupWhere(context.Background(), after, "session_id = ? and start_time = ?", []any{new.SessionId, new.StartTime}) require.NoError(err) assert.Equal(orig.(*State), after) }) @@ -249,7 +249,7 @@ func TestConnectionState_ImmutableFields(t *testing.T) { state := TestConnectionState(t, conn, connection.PublicId, StatusConnected) var new ConnectionState - err := rw.LookupWhere(context.Background(), &new, "connection_id = ? and state = ?", []interface{}{state.ConnectionId, state.Status}) + err := rw.LookupWhere(context.Background(), &new, "connection_id = ? and state = ?", []any{state.ConnectionId, state.Status}) require.NoError(t, err) tests := []struct { @@ -307,7 +307,7 @@ func TestConnectionState_ImmutableFields(t *testing.T) { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) orig := new.Clone() - err := rw.LookupWhere(context.Background(), orig, "connection_id = ? and start_time = ?", []interface{}{new.ConnectionId, new.StartTime}) + err := rw.LookupWhere(context.Background(), orig, "connection_id = ? and start_time = ?", []any{new.ConnectionId, new.StartTime}) require.NoError(err) rowsUpdated, err := rw.Update(context.Background(), tt.update, tt.fieldMask, nil, db.WithSkipVetForWrite(true)) @@ -320,7 +320,7 @@ func TestConnectionState_ImmutableFields(t *testing.T) { assert.Contains(err.Error(), tt.wantErrContains) } after := new.Clone() - err = rw.LookupWhere(context.Background(), after, "connection_id = ? and start_time = ?", []interface{}{new.ConnectionId, new.StartTime}) + err = rw.LookupWhere(context.Background(), after, "connection_id = ? and start_time = ?", []any{new.ConnectionId, new.StartTime}) require.NoError(err) assert.Equal(orig.(*ConnectionState), after) }) diff --git a/internal/session/job_session_cleanup.go b/internal/session/job_session_cleanup.go index 4dd13c3ea4..1ba42116d3 100644 --- a/internal/session/job_session_cleanup.go +++ b/internal/session/job_session_cleanup.go @@ -144,7 +144,7 @@ func (j *sessionConnectionCleanupJob) closeWorkerlessConnections(ctx context.Con db.ExpBackoff{}, func(reader db.Reader, w db.Writer) error { var err error - count, err = w.Exec(ctx, closeWorkerlessConnections, []interface{}{}) + count, err = w.Exec(ctx, closeWorkerlessConnections, []any{}) if err != nil { return errors.Wrap(ctx, err, op) } @@ -166,7 +166,7 @@ func (j *sessionConnectionCleanupJob) closeWorkerlessConnections(ctx context.Con // The only input to the method is the grace period, in seconds. func (j *sessionConnectionCleanupJob) closeConnectionsForDeadWorkers(ctx context.Context, gracePeriod time.Duration) ([]closeConnectionsForDeadWorkersResult, error) { const op = "session.(sessionConnectionCleanupJob).closeConnectionsForDeadWorkers" - args := []interface{}{ + args := []any{ sql.Named("grace_period_seconds", gracePeriod.Seconds()), } results := make([]closeConnectionsForDeadWorkersResult, 0) diff --git a/internal/session/query.go b/internal/session/query.go index 21c0015478..96447518d3 100644 --- a/internal/session/query.go +++ b/internal/session/query.go @@ -424,16 +424,16 @@ values ` ) -func batchInsertsessionCredentialDynamic(creds []*DynamicCredential) (string, []interface{}, error) { +func batchInsertsessionCredentialDynamic(creds []*DynamicCredential) (string, []any, error) { if len(creds) <= 0 { return "", nil, fmt.Errorf("empty slice of DynamicCredential, cannot build query") } batchInsertParams := make([]string, 0, len(creds)) - batchInsertArgs := make([]interface{}, 0, len(creds)*3) + batchInsertArgs := make([]any, 0, len(creds)*3) for _, cred := range creds { batchInsertParams = append(batchInsertParams, sessionCredentialDynamicBatchInsertValue) - batchInsertArgs = append(batchInsertArgs, []interface{}{cred.SessionId, cred.LibraryId, cred.CredentialPurpose}...) + batchInsertArgs = append(batchInsertArgs, []any{cred.SessionId, cred.LibraryId, cred.CredentialPurpose}...) } q := sessionCredentialDynamicBatchInsertBase + strings.Join(batchInsertParams, ",") + sessionCredentialDynamicBatchInsertReturning diff --git a/internal/session/repository.go b/internal/session/repository.go index c09ed4b338..9bcb644671 100644 --- a/internal/session/repository.go +++ b/internal/session/repository.go @@ -18,7 +18,7 @@ import ( // Clonable provides a cloning interface type Cloneable interface { - Clone() interface{} + Clone() any } // Repository is the session database repository @@ -72,9 +72,9 @@ func NewRepository(ctx context.Context, r db.Reader, w db.Writer, kms *kms.Kms, }, nil } -func (r *Repository) listPermissionWhereClauses() ([]string, []interface{}) { +func (r *Repository) listPermissionWhereClauses() ([]string, []any) { var where []string - var args []interface{} + var args []any if r.permissions == nil { return where, args diff --git a/internal/session/repository_connection.go b/internal/session/repository_connection.go index 6c8c6c4a8a..d6db89124e 100644 --- a/internal/session/repository_connection.go +++ b/internal/session/repository_connection.go @@ -59,7 +59,7 @@ func NewConnectionRepository(ctx context.Context, r db.Reader, w db.Writer, kms // list will return a listing of resources and honor the WithLimit option or the // repo defaultLimit. Supports WithOrder option. -func (r *ConnectionRepository) list(ctx context.Context, resources interface{}, where string, args []interface{}, opt ...Option) error { +func (r *ConnectionRepository) list(ctx context.Context, resources any, where string, args []any, opt ...Option) error { const op = "session.(ConnectionRepository).list" opts := getOpts(opt...) limit := r.defaultLimit @@ -106,7 +106,7 @@ func (r *ConnectionRepository) AuthorizeConnection(ctx context.Context, sessionI db.StdRetryCnt, db.ExpBackoff{}, func(reader db.Reader, w db.Writer) error { - rowsAffected, err := w.Exec(ctx, authorizeConnectionCte, []interface{}{ + rowsAffected, err := w.Exec(ctx, authorizeConnectionCte, []any{ sql.Named("session_id", sessionId), sql.Named("public_id", connectionId), sql.Named("worker_id", workerId), @@ -177,7 +177,7 @@ func (r *ConnectionRepository) ListConnectionsBySessionId(ctx context.Context, s return nil, errors.New(ctx, errors.InvalidParameter, op, "no session ID supplied") } var connections []*Connection - err := r.list(ctx, &connections, "session_id = ?", []interface{}{sessionId}, opt...) // pass options, so WithLimit and WithOrder are supported + err := r.list(ctx, &connections, "session_id = ?", []any{sessionId}, opt...) // pass options, so WithLimit and WithOrder are supported if err != nil { return nil, errors.Wrap(ctx, err, op) } @@ -351,7 +351,7 @@ func (r *ConnectionRepository) closeOrphanedConnections(ctx context.Context, wor var orphanedConns []string - args := make([]interface{}, 0, len(reportedConnections)+2) + args := make([]any, 0, len(reportedConnections)+2) args = append(args, sql.Named("worker_id", workerId)) args = append(args, sql.Named("worker_state_delay_seconds", r.workerStateDelay.Seconds())) @@ -396,7 +396,7 @@ func (r *ConnectionRepository) closeOrphanedConnections(ctx context.Context, wor func fetchConnectionStates(ctx context.Context, r db.Reader, connectionId string, opt ...db.Option) ([]*ConnectionState, error) { const op = "session.fetchConnectionStates" var states []*ConnectionState - if err := r.SearchWhere(ctx, &states, "connection_id = ?", []interface{}{connectionId}, opt...); err != nil { + if err := r.SearchWhere(ctx, &states, "connection_id = ?", []any{connectionId}, opt...); err != nil { return nil, errors.Wrap(ctx, err, op) } if len(states) == 0 { diff --git a/internal/session/repository_connection_test.go b/internal/session/repository_connection_test.go index 7321753061..1c7865721b 100644 --- a/internal/session/repository_connection_test.go +++ b/internal/session/repository_connection_test.go @@ -84,7 +84,7 @@ func TestRepository_ListConnection(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { i := AllocConnection(); return &i }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { i := AllocConnection(); return &i }(), "1=1") testConnections := []*Connection{} for i := 0; i < tt.createCnt; i++ { c := TestConnection(t, conn, @@ -109,7 +109,7 @@ func TestRepository_ListConnection(t *testing.T) { } t.Run("withOrder", func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { i := AllocConnection(); return &i }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { i := AllocConnection(); return &i }(), "1=1") wantCnt := 5 for i := 0; i < wantCnt; i++ { _ = TestConnection(t, conn, diff --git a/internal/session/repository_credential.go b/internal/session/repository_credential.go index e37c7461e1..d4296acfbf 100644 --- a/internal/session/repository_credential.go +++ b/internal/session/repository_credential.go @@ -29,7 +29,7 @@ func (r *Repository) AddSessionCredentials(ctx context.Context, sessProjectId, s return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get database wrapper")) } - addCreds := make([]interface{}, 0, len(credData)) + addCreds := make([]any, 0, len(credData)) for _, cred := range credData { if len(cred) == 0 { return errors.New(ctx, errors.InvalidParameter, op, "missing credential") @@ -74,7 +74,7 @@ func (r *Repository) ListSessionCredentials(ctx context.Context, sessProjectId, } var creds []*credential - if err := r.reader.SearchWhere(ctx, &creds, "session_id = ?", []interface{}{sessionId}); err != nil { + if err := r.reader.SearchWhere(ctx, &creds, "session_id = ?", []any{sessionId}); err != nil { return nil, errors.Wrap(ctx, err, op) } if len(creds) == 0 { diff --git a/internal/session/repository_session.go b/internal/session/repository_session.go index f0aa64751b..fee052ba2d 100644 --- a/internal/session/repository_session.go +++ b/internal/session/repository_session.go @@ -95,7 +95,7 @@ func (r *Repository) CreateSession(ctx context.Context, sessionWrapper wrapping. cred.SessionId = newSession.PublicId } - var staticCreds []interface{} + var staticCreds []any for _, cred := range newSession.StaticCredentials { cred.SessionId = newSession.PublicId staticCreds = append(staticCreds, cred) @@ -108,7 +108,7 @@ func (r *Repository) CreateSession(ctx context.Context, sessionWrapper wrapping. // Get static creds back from the db for return var c []*StaticCredential - if err := read.SearchWhere(ctx, &c, "session_id = ?", []interface{}{newSession.PublicId}); err != nil { + if err := read.SearchWhere(ctx, &c, "session_id = ?", []any{newSession.PublicId}); err != nil { return errors.Wrap(ctx, err, op) } returnedSession.StaticCredentials = c @@ -179,7 +179,7 @@ func (r *Repository) LookupSession(ctx context.Context, sessionId string, _ ...O session.States = states var dynamicCreds []*DynamicCredential - if err := read.SearchWhere(ctx, &dynamicCreds, "session_id = ?", []interface{}{sessionId}); err != nil { + if err := read.SearchWhere(ctx, &dynamicCreds, "session_id = ?", []any{sessionId}); err != nil { return errors.Wrap(ctx, err, op) } if len(dynamicCreds) > 0 { @@ -187,7 +187,7 @@ func (r *Repository) LookupSession(ctx context.Context, sessionId string, _ ...O } var staticCreds []*StaticCredential - if err := read.SearchWhere(ctx, &staticCreds, "session_id = ?", []interface{}{sessionId}); err != nil { + if err := read.SearchWhere(ctx, &staticCreds, "session_id = ?", []any{sessionId}); err != nil { return errors.Wrap(ctx, err, op) } if len(staticCreds) > 0 { @@ -401,7 +401,7 @@ func (r *Repository) terminateSessionIfPossible(ctx context.Context, sessionId s func(reader db.Reader, w db.Writer) error { var err error rowsAffected, err = w.Exec(ctx, terminateSessionIfPossible, - []interface{}{sql.Named("public_id", sessionId)}) + []any{sql.Named("public_id", sessionId)}) if err != nil { return errors.Wrap(ctx, err, op) } @@ -422,7 +422,7 @@ type AuthzSummary struct { func (r *Repository) sessionAuthzSummary(ctx context.Context, sessionId string) (*AuthzSummary, error) { const op = "session.(Repository).sessionAuthzSummary" - rows, err := r.reader.Query(ctx, remainingConnectionsCte, []interface{}{sql.Named("session_id", sessionId)}) + rows, err := r.reader.Query(ctx, remainingConnectionsCte, []any{sql.Named("session_id", sessionId)}) if err != nil { return nil, errors.Wrap(ctx, err, op) } @@ -466,7 +466,7 @@ func (r *Repository) ActivateSession(ctx context.Context, sessionId string, sess db.StdRetryCnt, db.ExpBackoff{}, func(reader db.Reader, w db.Writer) error { - rowsAffected, err := w.Exec(ctx, activateStateCte, []interface{}{ + rowsAffected, err := w.Exec(ctx, activateStateCte, []any{ sql.Named("session_id", sessionId), sql.Named("version", sessionVersion), }) @@ -564,7 +564,7 @@ func (r *Repository) updateState(ctx context.Context, sessionId string, sessionV updatedSession.CtTofuToken = nil } - rowsAffected, err = w.Exec(ctx, updateSessionState, []interface{}{ + rowsAffected, err = w.Exec(ctx, updateSessionState, []any{ sql.Named("session_id", sessionId), sql.Named("status", s.String()), }) @@ -597,7 +597,7 @@ func (r *Repository) checkIfNoLongerActive(ctx context.Context, reportedSessions const op = "session.(Repository).checkIfNotActive" notActive := make([]StateReport, 0, len(reportedSessions)) - args := make([]interface{}, 0, len(reportedSessions)) + args := make([]any, 0, len(reportedSessions)) var inClause string if len(reportedSessions) <= 0 { @@ -660,7 +660,7 @@ func (r *Repository) deleteSessionsTerminatedBefore(ctx context.Context, thresho func fetchStates(ctx context.Context, r db.Reader, sessionId string, opt ...db.Option) ([]*State, error) { const op = "session.fetchStates" var states []*State - if err := r.SearchWhere(ctx, &states, "session_id = ?", []interface{}{sessionId}, opt...); err != nil { + if err := r.SearchWhere(ctx, &states, "session_id = ?", []any{sessionId}, opt...); err != nil { return nil, errors.Wrap(ctx, err, op) } if len(states) == 0 { @@ -672,7 +672,7 @@ func fetchStates(ctx context.Context, r db.Reader, sessionId string, opt ...db.O func fetchConnections(ctx context.Context, r db.Reader, sessionId string, opt ...db.Option) ([]*Connection, error) { const op = "session.fetchConnections" var connections []*Connection - if err := r.SearchWhere(ctx, &connections, "session_id = ?", []interface{}{sessionId}, opt...); err != nil { + if err := r.SearchWhere(ctx, &connections, "session_id = ?", []any{sessionId}, opt...); err != nil { return nil, errors.Wrap(ctx, err, op) } if len(connections) == 0 { diff --git a/internal/session/repository_session_test.go b/internal/session/repository_session_test.go index 4191fdcf13..4e4f079228 100644 --- a/internal/session/repository_session_test.go +++ b/internal/session/repository_session_test.go @@ -152,7 +152,7 @@ func TestRepository_ListSession(t *testing.T) { repo, err := NewRepository(ctx, rw, rw, kms, WithLimit(testLimit), WithPermissions(tt.perms)) require.NoError(err) - db.TestDeleteWhere(t, conn, func() interface{} { i := AllocSession(); return &i }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { i := AllocSession(); return &i }(), "1=1") testSessions := []*Session{} for i := 0; i < tt.createCnt; i++ { s := TestSession(t, conn, wrapper, composedOf) @@ -188,7 +188,7 @@ func TestRepository_ListSession(t *testing.T) { } t.Run("withOrder", func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { i := AllocSession(); return &i }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { i := AllocSession(); return &i }(), "1=1") wantCnt := 5 for i := 0; i < wantCnt; i++ { _ = TestSession(t, conn, wrapper, composedOf) @@ -209,7 +209,7 @@ func TestRepository_ListSession(t *testing.T) { }) t.Run("onlySelf", func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { i := AllocSession(); return &i }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { i := AllocSession(); return &i }(), "1=1") wantCnt := 5 for i := 0; i < wantCnt; i++ { _ = TestSession(t, conn, wrapper, composedOf) @@ -245,7 +245,7 @@ func TestRepository_ListSessions_Multiple_Scopes(t *testing.T) { kms := kms.TestKms(t, conn, wrapper) ctx := context.Background() - db.TestDeleteWhere(t, conn, func() interface{} { i := AllocSession(); return &i }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { i := AllocSession(); return &i }(), "1=1") const numPerScope = 10 var p []perms.Permission @@ -866,7 +866,7 @@ func TestRepository_TerminateCompletedSessions(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { i := AllocSession(); return &i }(), "1=1") + db.TestDeleteWhere(t, conn, func() any { i := AllocSession(); return &i }(), "1=1") args := tt.setup() got, err := repo.TerminateCompletedSessions(context.Background()) @@ -1112,7 +1112,7 @@ func TestRepository_CancelSessionViaFKNull(t *testing.T) { } type cancelFk struct { s *Session - fkType interface{} + fkType any } tests := []struct { name string diff --git a/internal/session/session.go b/internal/session/session.go index 544c7ad524..b54835682a 100644 --- a/internal/session/session.go +++ b/internal/session/session.go @@ -169,7 +169,7 @@ func AllocSession() Session { } // Clone creates a clone of the Session -func (s *Session) Clone() interface{} { +func (s *Session) Clone() any { clone := &Session{ PublicId: s.PublicId, UserId: s.UserId, diff --git a/internal/session/state.go b/internal/session/state.go index 53709c9c9f..ece9d7b94a 100644 --- a/internal/session/state.go +++ b/internal/session/state.go @@ -87,7 +87,7 @@ func allocState() State { } // Clone creates a clone of the State -func (s *State) Clone() interface{} { +func (s *State) Clone() any { clone := &State{ SessionId: s.SessionId, Status: s.Status, diff --git a/internal/session/state_test.go b/internal/session/state_test.go index 4cdf76b4e7..e11e3897e7 100644 --- a/internal/session/state_test.go +++ b/internal/session/state_test.go @@ -125,7 +125,7 @@ func TestState_Delete(t *testing.T) { assert, require := assert.New(t), require.New(t) var initialState State - err := rw.LookupWhere(context.Background(), &initialState, "session_id = ? and state = ?", []interface{}{tt.state.SessionId, tt.state.Status}) + err := rw.LookupWhere(context.Background(), &initialState, "session_id = ? and state = ?", []any{tt.state.SessionId, tt.state.Status}) require.NoError(err) deleteState := allocState() @@ -147,7 +147,7 @@ func TestState_Delete(t *testing.T) { } assert.Equal(tt.wantRowsDeleted, deletedRows) foundState := allocState() - err = rw.LookupWhere(context.Background(), &foundState, "session_id = ? and start_time = ?", []interface{}{tt.state.SessionId, initialState.StartTime}) + err = rw.LookupWhere(context.Background(), &foundState, "session_id = ? and start_time = ?", []any{tt.state.SessionId, initialState.StartTime}) require.Error(err) assert.True(errors.IsNotFoundError(err)) }) diff --git a/internal/session/testing_test.go b/internal/session/testing_test.go index 0c262b0577..f129fb64b2 100644 --- a/internal/session/testing_test.go +++ b/internal/session/testing_test.go @@ -65,7 +65,7 @@ func Test_TestConnectionState(t *testing.T) { rw := db.New(conn) var initialState ConnectionState - err := rw.LookupWhere(context.Background(), &initialState, "connection_id = ? and state = ?", []interface{}{cs.ConnectionId, cs.Status}) + err := rw.LookupWhere(context.Background(), &initialState, "connection_id = ? and state = ?", []any{cs.ConnectionId, cs.Status}) require.NoError(err) assert.NotEmpty(initialState.StartTime) } diff --git a/internal/target/host_set.go b/internal/target/host_set.go index 8326dadda0..a728f5c899 100644 --- a/internal/target/host_set.go +++ b/internal/target/host_set.go @@ -45,7 +45,7 @@ func NewTargetHostSet(targetId, hostSetId string, _ ...Option) (*TargetHostSet, } // Clone creates a clone of the target host set -func (t *TargetHostSet) Clone() interface{} { +func (t *TargetHostSet) Clone() any { cp := proto.Clone(t.TargetHostSet) return &TargetHostSet{ TargetHostSet: cp.(*store.TargetHostSet), diff --git a/internal/target/repository.go b/internal/target/repository.go index c7175b3471..4f05157f8f 100644 --- a/internal/target/repository.go +++ b/internal/target/repository.go @@ -93,7 +93,7 @@ func (r *Repository) LookupTarget(ctx context.Context, publicIdOrName string, op } var where []string - var whereArgs []interface{} + var whereArgs []any nameEmpty := opts.WithName == "" projectIdEmpty := opts.WithProjectId == "" projectNameEmpty := opts.WithProjectName == "" @@ -171,7 +171,7 @@ func (r *Repository) FetchAuthzProtectedEntitiesByScope(ctx context.Context, pro const op = "target.(Repository).FetchAuthzProtectedEntitiesByScope" var where string - var args []interface{} + var args []any inClauseCnt := 0 @@ -254,9 +254,9 @@ func (r *Repository) ListTargets(ctx context.Context, opt ...Option) ([]Target, return targets, nil } -func (r *Repository) listPermissionWhereClauses() ([]string, []interface{}) { +func (r *Repository) listPermissionWhereClauses() ([]string, []any) { var where []string - var args []interface{} + var args []any inClauseCnt := 0 for _, p := range r.permissions { @@ -308,7 +308,7 @@ func (r *Repository) DeleteTarget(ctx context.Context, publicId string, _ ...Opt } var rowsDeleted int - var deleteResource interface{} + var deleteResource any _, err = r.writer.DoTx( ctx, db.StdRetryCnt, @@ -370,7 +370,7 @@ func (r *Repository) update(ctx context.Context, target Target, version uint32, dbOpts = append(dbOpts, db.WithOplog(oplogWrapper, metadata)) var rowsUpdated int - var returnedTarget interface{} + var returnedTarget any var hostSources []HostSource var credSources []CredentialSource _, err = r.writer.DoTx( @@ -461,7 +461,7 @@ func (r *Repository) CreateTarget(ctx context.Context, target Target, opt ...Opt } metadata := t.Oplog(oplog.OpType_OP_TYPE_CREATE) - var returnedTarget interface{} + var returnedTarget any var returnedHostSources []HostSource var returnedCredSources []CredentialSource _, err = r.writer.DoTx( @@ -530,7 +530,7 @@ func (r *Repository) UpdateTarget(ctx context.Context, target Target, version ui } var dbMask, nullFields []string dbMask, nullFields = dbw.BuildUpdatePaths( - map[string]interface{}{ + map[string]any{ "Name": target.GetName(), "Description": target.GetDescription(), "DefaultPort": target.GetDefaultPort(), diff --git a/internal/target/repository_credential_source.go b/internal/target/repository_credential_source.go index 124cd861f7..fac23638c0 100644 --- a/internal/target/repository_credential_source.go +++ b/internal/target/repository_credential_source.go @@ -60,7 +60,7 @@ func (r *Repository) AddTargetCredentialSources(ctx context.Context, targetId st var hostSources []HostSource var credSources []CredentialSource - var updatedTarget interface{} + var updatedTarget any _, err = r.writer.DoTx( ctx, db.StdRetryCnt, @@ -87,7 +87,7 @@ func (r *Repository) AddTargetCredentialSources(ctx context.Context, targetId st msgs = append(msgs, &targetOplogMsg) if len(addCredLibs) > 0 { - i := make([]interface{}, 0, len(addCredLibs)) + i := make([]any, 0, len(addCredLibs)) for _, cl := range addCredLibs { i = append(i, cl) } @@ -99,7 +99,7 @@ func (r *Repository) AddTargetCredentialSources(ctx context.Context, targetId st } if len(addStaticCreds) > 0 { - i := make([]interface{}, 0, len(addStaticCreds)) + i := make([]any, 0, len(addStaticCreds)) for _, c := range addStaticCreds { i = append(i, c) } @@ -196,7 +196,7 @@ func (r *Repository) DeleteTargetCredentialSources(ctx context.Context, targetId msgs = append(msgs, &targetOplogMsg) if len(deleteCredLibs) > 0 { - i := make([]interface{}, 0, len(deleteCredLibs)) + i := make([]any, 0, len(deleteCredLibs)) for _, cl := range deleteCredLibs { i = append(i, cl) } @@ -214,7 +214,7 @@ func (r *Repository) DeleteTargetCredentialSources(ctx context.Context, targetId } if len(deleteStaticCred) > 0 { - i := make([]interface{}, 0, len(deleteStaticCred)) + i := make([]any, 0, len(deleteStaticCred)) for _, cl := range deleteStaticCred { i = append(i, cl) } @@ -352,7 +352,7 @@ func (r *Repository) SetTargetCredentialSources(ctx context.Context, targetId st // add new credential libraries if len(addCredLibs) > 0 { - i := make([]interface{}, 0, len(addCredLibs)) + i := make([]any, 0, len(addCredLibs)) for _, cl := range addCredLibs { i = append(i, cl) } @@ -367,7 +367,7 @@ func (r *Repository) SetTargetCredentialSources(ctx context.Context, targetId st // delete existing credential libraries not part of set if len(delCredLibs) > 0 { - i := make([]interface{}, 0, len(delCredLibs)) + i := make([]any, 0, len(delCredLibs)) for _, cl := range delCredLibs { i = append(i, cl) } @@ -386,7 +386,7 @@ func (r *Repository) SetTargetCredentialSources(ctx context.Context, targetId st // add new static credential if len(addStaticCred) > 0 { - i := make([]interface{}, 0, len(addStaticCred)) + i := make([]any, 0, len(addStaticCred)) for _, cl := range addStaticCred { i = append(i, cl) } @@ -401,7 +401,7 @@ func (r *Repository) SetTargetCredentialSources(ctx context.Context, targetId st // delete existing static credentials not part of set if len(delStaticCred) > 0 { - i := make([]interface{}, 0, len(delStaticCred)) + i := make([]any, 0, len(delStaticCred)) for _, cl := range delStaticCred { i = append(i, cl) } @@ -455,7 +455,7 @@ func (r *Repository) changes(ctx context.Context, targetId string, ids []string, // TODO ensure that all cls have the same purpose as the given purpose? var inClauseSpots []string - var params []interface{} + var params []any params = append(params, sql.Named("target_id", targetId), sql.Named("purpose", purpose)) for idx, id := range ids { params = append(params, sql.Named(fmt.Sprintf("%d", idx+1), id)) @@ -509,7 +509,7 @@ func (r *Repository) changes(ctx context.Context, targetId string, ids []string, func fetchCredentialSources(ctx context.Context, r db.Reader, targetId string) ([]CredentialSource, error) { const op = "target.fetchCredentialSources" var sources []*TargetCredentialSource - if err := r.SearchWhere(ctx, &sources, "target_id = ?", []interface{}{targetId}); err != nil { + if err := r.SearchWhere(ctx, &sources, "target_id = ?", []any{targetId}); err != nil { return nil, errors.Wrap(ctx, err, op) } if len(sources) == 0 { @@ -535,7 +535,7 @@ func (r *Repository) createSources(ctx context.Context, tId string, tSubtype sub // Fetch credentials from database to determine the type of credential var credView []*credentialSourceView - if err := r.reader.SearchWhere(ctx, &credView, "public_id in (?)", []interface{}{ids}); err != nil { + if err := r.reader.SearchWhere(ctx, &credView, "public_id in (?)", []any{ids}); err != nil { return nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("can't retrieve credentials")) } if len(ids) != len(credView) { diff --git a/internal/target/repository_host_source.go b/internal/target/repository_host_source.go index 8fd42c268a..338431ed2f 100644 --- a/internal/target/repository_host_source.go +++ b/internal/target/repository_host_source.go @@ -26,7 +26,7 @@ func (r *Repository) AddTargetHostSources(ctx context.Context, targetId string, if len(hostSourceIds) == 0 { return nil, nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing host source ids") } - newHostSources := make([]interface{}, 0, len(hostSourceIds)) + newHostSources := make([]any, 0, len(hostSourceIds)) for _, id := range hostSourceIds { ths, err := NewTargetHostSet(targetId, id) if err != nil { @@ -58,7 +58,7 @@ func (r *Repository) AddTargetHostSources(ctx context.Context, targetId string, } var currentHostSources []HostSource var currentCredSources []CredentialSource - var updatedTarget interface{} + var updatedTarget any _, err = r.writer.DoTx( ctx, db.StdRetryCnt, @@ -121,7 +121,7 @@ func (r *Repository) DeleteTargetHostSources(ctx context.Context, targetId strin if len(hostSourceIds) == 0 { return db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing host source ids") } - deleteTargetHostSources := make([]interface{}, 0, len(hostSourceIds)) + deleteTargetHostSources := make([]any, 0, len(hostSourceIds)) for _, id := range hostSourceIds { ths, err := NewTargetHostSet(targetId, id) if err != nil { @@ -231,7 +231,7 @@ func (r *Repository) SetTargetHostSources(ctx context.Context, targetId string, for _, s := range foundThs { found[s.Id()] = s } - addHostSources := make([]interface{}, 0, len(hostSourceIds)) + addHostSources := make([]any, 0, len(hostSourceIds)) for _, id := range hostSourceIds { if _, ok := found[id]; ok { // found a match, so do nothing (we want to keep it), but remove it @@ -245,7 +245,7 @@ func (r *Repository) SetTargetHostSources(ctx context.Context, targetId string, } addHostSources = append(addHostSources, hs) } - deleteHostSources := make([]interface{}, 0, len(hostSourceIds)) + deleteHostSources := make([]any, 0, len(hostSourceIds)) if len(found) > 0 { for _, s := range found { hs, err := NewTargetHostSet(targetId, s.Id()) @@ -350,7 +350,7 @@ func (r *Repository) SetTargetHostSources(ctx context.Context, targetId string, func fetchHostSources(ctx context.Context, r db.Reader, targetId string) ([]HostSource, error) { const op = "target.fetchHostSources" var hostSets []*TargetSet - if err := r.SearchWhere(ctx, &hostSets, "target_id = ?", []interface{}{targetId}); err != nil { + if err := r.SearchWhere(ctx, &hostSets, "target_id = ?", []any{targetId}); err != nil { return nil, errors.Wrap(ctx, err, op) } // FIXME: When we have direct host additions, there will need to be an diff --git a/internal/target/targettest/target.go b/internal/target/targettest/target.go index 93067657a2..447da210c6 100644 --- a/internal/target/targettest/target.go +++ b/internal/target/targettest/target.go @@ -272,7 +272,7 @@ func TestNewTestTarget(ctx context.Context, t *testing.T, conn *db.DB, projectId require.NoError(err) if len(opts.WithHostSources) > 0 { - newHostSets := make([]interface{}, 0, len(opts.WithHostSources)) + newHostSets := make([]any, 0, len(opts.WithHostSources)) for _, s := range opts.WithHostSources { hostSet, err := target.NewTargetHostSet(tar.GetPublicId(), s) require.NoError(err) @@ -282,7 +282,7 @@ func TestNewTestTarget(ctx context.Context, t *testing.T, conn *db.DB, projectId require.NoError(err) } if len(opts.WithCredentialLibraries) > 0 { - newCredLibs := make([]interface{}, 0, len(opts.WithCredentialLibraries)) + newCredLibs := make([]any, 0, len(opts.WithCredentialLibraries)) for _, cl := range opts.WithCredentialLibraries { cl.TargetId = tar.GetPublicId() newCredLibs = append(newCredLibs, cl) diff --git a/internal/target/tcp/immutable_fields_test.go b/internal/target/tcp/immutable_fields_test.go index ae23a025cb..a9f8dcd5bd 100644 --- a/internal/target/tcp/immutable_fields_test.go +++ b/internal/target/tcp/immutable_fields_test.go @@ -219,7 +219,7 @@ func TestTargetHostSet_ImmutableFields(t *testing.T) { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) orig := new.Clone() - err := rw.LookupWhere(context.Background(), orig, "target_id = ? and host_set_id = ?", []interface{}{new.TargetId, new.HostSetId}) + err := rw.LookupWhere(context.Background(), orig, "target_id = ? and host_set_id = ?", []any{new.TargetId, new.HostSetId}) require.NoError(err) rowsUpdated, err := rw.Update(context.Background(), tt.update, tt.fieldMask, nil, db.WithSkipVetForWrite(true)) @@ -227,7 +227,7 @@ func TestTargetHostSet_ImmutableFields(t *testing.T) { assert.Equal(0, rowsUpdated) after := new.Clone() - err = rw.LookupWhere(context.Background(), after, "target_id = ? and host_set_id = ?", []interface{}{new.TargetId, new.HostSetId}) + err = rw.LookupWhere(context.Background(), after, "target_id = ? and host_set_id = ?", []any{new.TargetId, new.HostSetId}) require.NoError(err) assert.True(proto.Equal(orig.(*target.TargetHostSet), after.(*target.TargetHostSet))) }) diff --git a/internal/target/tcp/repository_host_source_test.go b/internal/target/tcp/repository_host_source_test.go index be2fa10f87..09c60c936e 100644 --- a/internal/target/tcp/repository_host_source_test.go +++ b/internal/target/tcp/repository_host_source_test.go @@ -93,7 +93,7 @@ func TestRepository_AddTargetHostSets(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { assert, require := assert.New(t), require.New(t) - db.TestDeleteWhere(t, conn, func() interface{} { i := allocTargetHostSet(); return &i }(), "1 = 1") + db.TestDeleteWhere(t, conn, func() any { i := allocTargetHostSet(); return &i }(), "1 = 1") db.TestDeleteWhere(t, conn, tcp.NewTestTarget(""), "1 = 1") ctx := context.Background() diff --git a/internal/target/tcp/testing.go b/internal/target/tcp/testing.go index 19d076fd1a..f127a4bc14 100644 --- a/internal/target/tcp/testing.go +++ b/internal/target/tcp/testing.go @@ -27,7 +27,7 @@ func TestTarget(ctx context.Context, t testing.TB, conn *db.DB, projectId, name require.NoError(err) if len(opts.WithHostSources) > 0 { - newHostSets := make([]interface{}, 0, len(opts.WithHostSources)) + newHostSets := make([]any, 0, len(opts.WithHostSources)) for _, s := range opts.WithHostSources { hostSet, err := target.NewTargetHostSet(tar.GetPublicId(), s) require.NoError(err) @@ -37,7 +37,7 @@ func TestTarget(ctx context.Context, t testing.TB, conn *db.DB, projectId, name require.NoError(err) } if len(opts.WithCredentialLibraries) > 0 { - newCredLibs := make([]interface{}, 0, len(opts.WithCredentialLibraries)) + newCredLibs := make([]any, 0, len(opts.WithCredentialLibraries)) for _, cl := range opts.WithCredentialLibraries { cl.TargetId = tar.GetPublicId() newCredLibs = append(newCredLibs, cl) @@ -46,7 +46,7 @@ func TestTarget(ctx context.Context, t testing.TB, conn *db.DB, projectId, name require.NoError(err) } if len(opts.WithStaticCredentials) > 0 { - newCreds := make([]interface{}, 0, len(opts.WithStaticCredentials)) + newCreds := make([]any, 0, len(opts.WithStaticCredentials)) for _, c := range opts.WithStaticCredentials { c.TargetId = tar.GetPublicId() newCreds = append(newCreds, c) diff --git a/internal/tests/api/accounts/account_test.go b/internal/tests/api/accounts/account_test.go index f066a33e38..8589a812c3 100644 --- a/internal/tests/api/accounts/account_test.go +++ b/internal/tests/api/accounts/account_test.go @@ -40,7 +40,7 @@ func TestListPassword(t *testing.T) { expected := lr.Items assert.Len(expected, 0) - expected = append(expected, &accounts.Account{Attributes: map[string]interface{}{"login_name": "loginname0"}}) + expected = append(expected, &accounts.Account{Attributes: map[string]any{"login_name": "loginname0"}}) cr, err := accountClient.Create(tc.Context(), am.Id, accounts.WithPasswordAccountLoginName(expected[0].Attributes["login_name"].(string))) require.NoError(err) diff --git a/internal/tests/api/authmethods/authenticate_test.go b/internal/tests/api/authmethods/authenticate_test.go index 997096daa6..c36e7ed93e 100644 --- a/internal/tests/api/authmethods/authenticate_test.go +++ b/internal/tests/api/authmethods/authenticate_test.go @@ -40,19 +40,19 @@ func TestAuthenticate(t *testing.T) { client := tc.Client() methods := authmethods.NewClient(client) - tok, err := methods.Authenticate(tc.Context(), tc.Server().DevPasswordAuthMethodId, "login", map[string]interface{}{"login_name": "user", "password": "passpass"}) + tok, err := methods.Authenticate(tc.Context(), tc.Server().DevPasswordAuthMethodId, "login", map[string]any{"login_name": "user", "password": "passpass"}) require.NoError(err) assert.NotNil(tok) - _, err = methods.Authenticate(tc.Context(), tc.Server().DevPasswordAuthMethodId, "login", map[string]interface{}{"login_name": "user", "password": "wrong"}) + _, err = methods.Authenticate(tc.Context(), tc.Server().DevPasswordAuthMethodId, "login", map[string]any{"login_name": "user", "password": "wrong"}) require.Error(err) apiErr := api.AsServerError(err) require.NotNil(apiErr) assert.EqualValuesf(http.StatusUnauthorized, apiErr.Response().StatusCode(), "Expected unauthorized, got %q", apiErr.Message) // Also ensure that, for now, using "credentials" still works, as well as no command. - reqBody := map[string]interface{}{ - "attributes": map[string]interface{}{"login_name": "user", "password": "passpass"}, + reqBody := map[string]any{ + "attributes": map[string]any{"login_name": "user", "password": "passpass"}, } req, err := client.NewRequest(tc.Context(), "POST", fmt.Sprintf("auth-methods/%s:authenticate", tc.Server().DevPasswordAuthMethodId), reqBody) require.NoError(err) @@ -71,7 +71,7 @@ func TestAuthenticate(t *testing.T) { require.NotNil(eventConfig.AuditEvents) _ = os.WriteFile(eventConfig.AuditEvents.Name(), nil, 0o666) // clean out audit events from previous calls - tok, err = methods.Authenticate(tc.Context(), tc.Server().DevPasswordAuthMethodId, "login", map[string]interface{}{"login_name": "user", "password": "passpass"}) + tok, err = methods.Authenticate(tc.Context(), tc.Server().DevPasswordAuthMethodId, "login", map[string]any{"login_name": "user", "password": "passpass"}) require.NoError(err) assert.NotNil(tok) got := tests_api.CloudEventFromFile(t, eventConfig.AuditEvents.Name()) @@ -79,19 +79,19 @@ func TestAuthenticate(t *testing.T) { // All attribute fields are classified for now. reqDetails := tests_api.GetEventDetails(t, got, "request") tests_api.AssertRedactedValues(t, reqDetails) - tests_api.AssertRedactedValues(t, reqDetails["Attrs"].(map[string]interface{})["PasswordLoginAttributes"], "password", "login_name") + tests_api.AssertRedactedValues(t, reqDetails["Attrs"].(map[string]any)["PasswordLoginAttributes"], "password", "login_name") respDetails := tests_api.GetEventDetails(t, got, "response") tests_api.AssertRedactedValues(t, respDetails) - tests_api.AssertRedactedValues(t, respDetails["Attrs"].(map[string]interface{})["AuthTokenResponse"], "token") + tests_api.AssertRedactedValues(t, respDetails["Attrs"].(map[string]any)["AuthTokenResponse"], "token") _ = os.WriteFile(eventConfig.AuditEvents.Name(), nil, 0o666) // clean out audit events from previous calls - tok, err = methods.Authenticate(tc.Context(), tc.Server().DevPasswordAuthMethodId, "login", map[string]interface{}{"login_name": "user", "password": "bad-pass"}) + tok, err = methods.Authenticate(tc.Context(), tc.Server().DevPasswordAuthMethodId, "login", map[string]any{"login_name": "user", "password": "bad-pass"}) require.Error(err) assert.Nil(tok) got = tests_api.CloudEventFromFile(t, eventConfig.AuditEvents.Name()) reqDetails = tests_api.GetEventDetails(t, got, "request") tests_api.AssertRedactedValues(t, reqDetails) - tests_api.AssertRedactedValues(t, reqDetails["Attrs"].(map[string]interface{})["PasswordLoginAttributes"], "password", "login_name") + tests_api.AssertRedactedValues(t, reqDetails["Attrs"].(map[string]any)["PasswordLoginAttributes"], "password", "login_name") } diff --git a/internal/tests/api/authmethods/authmethod_test.go b/internal/tests/api/authmethods/authmethod_test.go index ec48119b4a..7d489422f7 100644 --- a/internal/tests/api/authmethods/authmethod_test.go +++ b/internal/tests/api/authmethods/authmethod_test.go @@ -67,15 +67,15 @@ func TestCrud(t *testing.T) { checkAuthMethod("create", pw.Item, "bar", 1) got := tests_api.CloudEventFromFile(t, eventConfig.AuditEvents.Name()) - reqItem := tests_api.GetEventDetails(t, got, "request")["item"].(map[string]interface{}) + reqItem := tests_api.GetEventDetails(t, got, "request")["item"].(map[string]any) tests_api.AssertRedactedValues(t, reqItem) tests_api.AssertRedactedValues(t, reqItem["Attrs"]) - tests_api.AssertRedactedValues(t, reqItem["Attrs"].(map[string]interface{})["PasswordAuthMethodAttributes"]) + tests_api.AssertRedactedValues(t, reqItem["Attrs"].(map[string]any)["PasswordAuthMethodAttributes"]) - respItem := tests_api.GetEventDetails(t, got, "response")["item"].(map[string]interface{}) + respItem := tests_api.GetEventDetails(t, got, "response")["item"].(map[string]any) tests_api.AssertRedactedValues(t, respItem) tests_api.AssertRedactedValues(t, respItem["Attrs"]) - tests_api.AssertRedactedValues(t, respItem["Attrs"].(map[string]interface{})["PasswordAuthMethodAttributes"]) + tests_api.AssertRedactedValues(t, respItem["Attrs"].(map[string]any)["PasswordAuthMethodAttributes"]) _ = os.WriteFile(eventConfig.AuditEvents.Name(), nil, 0o666) // clean out audit events from previous calls pw, err = amClient.Read(tc.Context(), pw.Item.Id) @@ -85,10 +85,10 @@ func TestCrud(t *testing.T) { got = tests_api.CloudEventFromFile(t, eventConfig.AuditEvents.Name()) tests_api.AssertRedactedValues(t, tests_api.GetEventDetails(t, got, "request")) - respItem = tests_api.GetEventDetails(t, got, "response")["item"].(map[string]interface{}) + respItem = tests_api.GetEventDetails(t, got, "response")["item"].(map[string]any) tests_api.AssertRedactedValues(t, respItem) tests_api.AssertRedactedValues(t, respItem["Attrs"]) - tests_api.AssertRedactedValues(t, respItem["Attrs"].(map[string]interface{})["PasswordAuthMethodAttributes"]) + tests_api.AssertRedactedValues(t, respItem["Attrs"].(map[string]any)["PasswordAuthMethodAttributes"]) _ = os.WriteFile(eventConfig.AuditEvents.Name(), nil, 0o666) // clean out audit events from previous calls pw, err = amClient.Update(tc.Context(), pw.Item.Id, pw.Item.Version, authmethods.WithName("buz")) @@ -96,12 +96,12 @@ func TestCrud(t *testing.T) { checkAuthMethod("update", pw.Item, "buz", 2) got = tests_api.CloudEventFromFile(t, eventConfig.AuditEvents.Name()) - tests_api.AssertRedactedValues(t, tests_api.GetEventDetails(t, got, "request")["item"].(map[string]interface{})) + tests_api.AssertRedactedValues(t, tests_api.GetEventDetails(t, got, "request")["item"].(map[string]any)) - respItem = tests_api.GetEventDetails(t, got, "response")["item"].(map[string]interface{}) + respItem = tests_api.GetEventDetails(t, got, "response")["item"].(map[string]any) tests_api.AssertRedactedValues(t, respItem) tests_api.AssertRedactedValues(t, respItem["Attrs"]) - tests_api.AssertRedactedValues(t, respItem["Attrs"].(map[string]interface{})["PasswordAuthMethodAttributes"]) + tests_api.AssertRedactedValues(t, respItem["Attrs"].(map[string]any)["PasswordAuthMethodAttributes"]) pw, err = amClient.Update(tc.Context(), pw.Item.Id, pw.Item.Version, authmethods.DefaultName()) require.NoError(err) @@ -123,15 +123,15 @@ func TestCrud(t *testing.T) { checkAuthMethod("create", oidc.Item, "foo", 1) got = tests_api.CloudEventFromFile(t, eventConfig.AuditEvents.Name()) - reqItem = tests_api.GetEventDetails(t, got, "request")["item"].(map[string]interface{}) + reqItem = tests_api.GetEventDetails(t, got, "request")["item"].(map[string]any) tests_api.AssertRedactedValues(t, reqItem) tests_api.AssertRedactedValues(t, reqItem["Attrs"]) - tests_api.AssertRedactedValues(t, reqItem["Attrs"].(map[string]interface{})["OidcAuthMethodsAttributes"]) + tests_api.AssertRedactedValues(t, reqItem["Attrs"].(map[string]any)["OidcAuthMethodsAttributes"]) - respItem = tests_api.GetEventDetails(t, got, "response")["item"].(map[string]interface{}) + respItem = tests_api.GetEventDetails(t, got, "response")["item"].(map[string]any) tests_api.AssertRedactedValues(t, respItem) tests_api.AssertRedactedValues(t, respItem["Attrs"]) - tests_api.AssertRedactedValues(t, respItem["Attrs"].(map[string]interface{})["OidcAuthMethodsAttributes"]) + tests_api.AssertRedactedValues(t, respItem["Attrs"].(map[string]any)["OidcAuthMethodsAttributes"]) oidc, err = amClient.Read(tc.Context(), oidc.Item.Id) require.NoError(err) @@ -295,11 +295,11 @@ func TestCustomMethods(t *testing.T) { reqDetails := tests_api.GetEventDetails(t, got, "request") tests_api.AssertRedactedValues(t, reqDetails) tests_api.AssertRedactedValues(t, reqDetails["Attrs"]) - tests_api.AssertRedactedValues(t, reqDetails["Attrs"].(map[string]interface{})["OidcChangeStateAttributes"]) + tests_api.AssertRedactedValues(t, reqDetails["Attrs"].(map[string]any)["OidcChangeStateAttributes"]) - respItem := tests_api.GetEventDetails(t, got, "response")["item"].(map[string]interface{}) + respItem := tests_api.GetEventDetails(t, got, "response")["item"].(map[string]any) tests_api.AssertRedactedValues(t, respItem) - tests_api.AssertRedactedValues(t, respItem["Attrs"].(map[string]interface{})["OidcAuthMethodsAttributes"]) + tests_api.AssertRedactedValues(t, respItem["Attrs"].(map[string]any)["OidcAuthMethodsAttributes"]) _, err = amClient.ChangeState(tc.Context(), u.Item.Id, u.Item.Version, "", authmethods.WithOidcAuthMethodDisableDiscoveredConfigValidation(true)) assert.Error(err) @@ -364,7 +364,7 @@ func TestErrors(t *testing.T) { assert.EqualValues(http.StatusBadRequest, apiErr.Response().StatusCode()) // Passing in a invalid authentication method sub-type should return an error - _, err = amClient.Authenticate(tc.Context(), "ampwd_1234567890", "login", map[string]interface{}{ + _, err = amClient.Authenticate(tc.Context(), "ampwd_1234567890", "login", map[string]any{ "login_name": "admin", "password": "password", }) diff --git a/internal/tests/api/authtokens/authtoken_test.go b/internal/tests/api/authtokens/authtoken_test.go index 2341f73d5d..46fdf2ce39 100644 --- a/internal/tests/api/authtokens/authtoken_test.go +++ b/internal/tests/api/authtokens/authtoken_test.go @@ -67,7 +67,7 @@ func TestList(t *testing.T) { var expected []*authtokens.AuthToken methods := authmethods.NewClient(client) - result, err := methods.Authenticate(tc.Context(), amId, "login", map[string]interface{}{"login_name": "user", "password": "passpass"}) + result, err := methods.Authenticate(tc.Context(), amId, "login", map[string]any{"login_name": "user", "password": "passpass"}) require.NoError(err) token = new(authtokens.AuthToken) require.NoError(json.Unmarshal(result.GetRawAttributes(), token)) @@ -78,7 +78,7 @@ func TestList(t *testing.T) { assert.ElementsMatch(comparableSlice(expected), comparableSlice(atl.Items)) for i := 1; i < 10; i++ { - result, err = methods.Authenticate(tc.Context(), amId, "login", map[string]interface{}{"login_name": "user", "password": "passpass"}) + result, err = methods.Authenticate(tc.Context(), amId, "login", map[string]any{"login_name": "user", "password": "passpass"}) require.NoError(err) token = new(authtokens.AuthToken) require.NoError(json.Unmarshal(result.GetRawAttributes(), token)) @@ -130,7 +130,7 @@ func TestCrud(t *testing.T) { tokens := authtokens.NewClient(client) methods := authmethods.NewClient(client) - result, err := methods.Authenticate(tc.Context(), tc.Server().DevPasswordAuthMethodId, "login", map[string]interface{}{"login_name": "user", "password": "passpass"}) + result, err := methods.Authenticate(tc.Context(), tc.Server().DevPasswordAuthMethodId, "login", map[string]any{"login_name": "user", "password": "passpass"}) require.NoError(err) wantToken := new(authtokens.AuthToken) require.NoError(json.Unmarshal(result.GetRawAttributes(), wantToken)) diff --git a/internal/tests/api/credentiallibraries/credentiallibrary_test.go b/internal/tests/api/credentiallibraries/credentiallibrary_test.go index 0e1b74be33..2016c92be2 100644 --- a/internal/tests/api/credentiallibraries/credentiallibrary_test.go +++ b/internal/tests/api/credentiallibraries/credentiallibrary_test.go @@ -41,7 +41,7 @@ func TestList(t *testing.T) { var expected []*credentiallibraries.CredentialLibrary for i := 0; i < 10; i++ { - expected = append(expected, &credentiallibraries.CredentialLibrary{Name: fmt.Sprint(i), Attributes: map[string]interface{}{"vault_path": "something"}}) + expected = append(expected, &credentiallibraries.CredentialLibrary{Name: fmt.Sprint(i), Attributes: map[string]any{"vault_path": "something"}}) } cl, err := lClient.Create(tc.Context(), cs.Item.Id, credentiallibraries.WithName(expected[0].Name), credentiallibraries.WithVaultCredentialLibraryPath("something")) diff --git a/internal/tests/api/credentials/credentials_test.go b/internal/tests/api/credentials/credentials_test.go index b51b91b70b..fa09f5c5c8 100644 --- a/internal/tests/api/credentials/credentials_test.go +++ b/internal/tests/api/credentials/credentials_test.go @@ -255,7 +255,7 @@ func TestCrudJson(t *testing.T) { } credClient := credentials.NewClient(client) - obj := map[string]interface{}{ + obj := map[string]any{ "username": "admin", "password": "pass", } @@ -303,7 +303,7 @@ func TestCrudJson(t *testing.T) { require.NotNil(cs) checkResource("update", cred.Item, "bar", 2) - cred, err = credClient.Update(tc.Context(), cred.Item.Id, cred.Item.Version, credentials.WithJsonCredentialObject(map[string]interface{}{ + cred, err = credClient.Update(tc.Context(), cred.Item.Id, cred.Item.Version, credentials.WithJsonCredentialObject(map[string]any{ "username": "not_admin", "password": "not_password", })) diff --git a/internal/tests/api/credentialstores/credentialstore_test.go b/internal/tests/api/credentialstores/credentialstore_test.go index 05500d61e7..300bfe329e 100644 --- a/internal/tests/api/credentialstores/credentialstore_test.go +++ b/internal/tests/api/credentialstores/credentialstore_test.go @@ -35,7 +35,7 @@ func TestList(t *testing.T) { var expected []*credentialstores.CredentialStore for i := 0; i < 10; i++ { _, tok := vaultServ.CreateToken(t) - expected = append(expected, &credentialstores.CredentialStore{Name: fmt.Sprint(i), Attributes: map[string]interface{}{ + expected = append(expected, &credentialstores.CredentialStore{Name: fmt.Sprint(i), Attributes: map[string]any{ "address": vaultServ.Addr, "token": tok, }}) @@ -135,7 +135,7 @@ func TestCrud(t *testing.T) { // credential store with an expired token is correctly returned over the API rw := db.New(tc.DbConn()) num, err := rw.Exec(tc.Context(), "update credential_vault_token set status = ? where store_id = ?", - []interface{}{vault.ExpiredToken, cs.GetItem().Id}) + []any{vault.ExpiredToken, cs.GetItem().Id}) require.NoError(err) assert.Equal(1, num) vaultServ.RevokeToken(t, vaultTok) diff --git a/internal/tests/api/hostcatalogs/host_catalog_test.go b/internal/tests/api/hostcatalogs/host_catalog_test.go index 43d577437c..81a30cf92a 100644 --- a/internal/tests/api/hostcatalogs/host_catalog_test.go +++ b/internal/tests/api/hostcatalogs/host_catalog_test.go @@ -169,12 +169,12 @@ func TestCrud(t *testing.T) { // Plugin catalogs c, err := hcClient.Create(tc.Context(), "plugin", proj.GetPublicId(), hostcatalogs.WithName("pluginfoo"), hostcatalogs.WithPluginId("pl_1234567890"), - hostcatalogs.WithAttributes(map[string]interface{}{"foo": "bar"})) + hostcatalogs.WithAttributes(map[string]any{"foo": "bar"})) require.NoError(err) c, err = hcClient.Update(tc.Context(), c.Item.Id, c.Item.Version, hostcatalogs.WithName("bar"), - hostcatalogs.WithAttributes(map[string]interface{}{"key": "val", "foo": nil}), - hostcatalogs.WithSecrets(map[string]interface{}{"secretkey": "secretval"})) + hostcatalogs.WithAttributes(map[string]any{"key": "val", "foo": nil}), + hostcatalogs.WithSecrets(map[string]any{"secretkey": "secretval"})) checkCatalog("update", c.Item, err, "bar", 2) assert.Contains(c.Item.Attributes, "key") assert.NotContains(c.Item.Attributes, "foo") @@ -184,7 +184,7 @@ func TestCrud(t *testing.T) { checkCatalog("update", c.Item, err, "", 3) c, err = hcClient.Update(tc.Context(), c.Item.Id, 0, hostcatalogs.WithAutomaticVersioning(true), - hostcatalogs.WithSecrets(map[string]interface{}{ + hostcatalogs.WithSecrets(map[string]any{ "key1": "val1", "key2": "val2", })) diff --git a/internal/tests/api/hosts/host_test.go b/internal/tests/api/hosts/host_test.go index 2d8ab9afe9..7f683b9589 100644 --- a/internal/tests/api/hosts/host_test.go +++ b/internal/tests/api/hosts/host_test.go @@ -97,14 +97,14 @@ func TestPluginHosts(t *testing.T) { require.NoError(err) require.NotNil(hc) - hset, err := hostsets.NewClient(client).Create(tc.Context(), hc.Item.Id, hostsets.WithAttributes(map[string]interface{}{ - "host_info": []interface{}{ - map[string]interface{}{ + hset, err := hostsets.NewClient(client).Create(tc.Context(), hc.Item.Id, hostsets.WithAttributes(map[string]any{ + "host_info": []any{ + map[string]any{ "external_id": "test1", "ip_addresses": []string{"10.0.0.1", "192.168.1.1"}, "dns_names": []string{"foo.hashicorp.com", "boundaryproject.io"}, }, - map[string]interface{}{ + map[string]any{ "external_id": "test2", "ip_addresses": []string{"10.0.0.2", "192.168.1.2"}, "dns_names": []string{"foo2.hashicorp.com", "boundaryproject2.io"}, diff --git a/internal/tests/api/hostsets/host_set_test.go b/internal/tests/api/hostsets/host_set_test.go index 2a9afb8106..91cbf88c19 100644 --- a/internal/tests/api/hostsets/host_set_test.go +++ b/internal/tests/api/hostsets/host_set_test.go @@ -247,11 +247,11 @@ func TestCrud(t *testing.T) { // Plugin Sets c, err := hcClient.Create(tc.Context(), "plugin", proj.GetPublicId(), hostcatalogs.WithName("pluginfoo"), hostcatalogs.WithPluginId("pl_1234567890"), - hostcatalogs.WithAttributes(map[string]interface{}{"foo": "bar"})) + hostcatalogs.WithAttributes(map[string]any{"foo": "bar"})) require.NoError(err) h, err = hClient.Create(tc.Context(), c.Item.Id, hostsets.WithName("foo"), - hostsets.WithAttributes(map[string]interface{}{"foo": "bar"}), hostsets.WithPreferredEndpoints([]string{"dns:test"}), + hostsets.WithAttributes(map[string]any{"foo": "bar"}), hostsets.WithPreferredEndpoints([]string{"dns:test"}), hostsets.WithSyncIntervalSeconds(-1)) require.NoError(err) assert.Equal("foo", h.Item.Name) @@ -264,13 +264,13 @@ func TestCrud(t *testing.T) { assert.Contains([]uint32{1, 2}, h.Item.Version) h = retryableUpdate(hClient, h.Item.Id, h.Item.Version, hostsets.WithName("bar"), - hostsets.WithAttributes(map[string]interface{}{"foo": nil, "key": "val"}), + hostsets.WithAttributes(map[string]any{"foo": nil, "key": "val"}), hostsets.WithPreferredEndpoints([]string{"dns:update"})) assert.Equal("bar", h.Item.Name) // If the plugin set has synced since creation, its version will be 3; otherwise it will be 2. assert.Contains([]uint32{2, 3}, h.Item.Version) - assert.Equal(h.Item.Attributes, map[string]interface{}{"key": "val"}) + assert.Equal(h.Item.Attributes, map[string]any{"key": "val"}) assert.Equal(h.Item.PreferredEndpoints, []string{"dns:update"}) h = retryableUpdate(hClient, h.Item.Id, h.Item.Version, hostsets.WithSyncIntervalSeconds(42)) diff --git a/internal/tests/api/testing.go b/internal/tests/api/testing.go index 0552d10c7d..bd3a9f197a 100644 --- a/internal/tests/api/testing.go +++ b/internal/tests/api/testing.go @@ -26,27 +26,27 @@ func CloudEventFromFile(t testing.TB, fileName string) *cloudevents.Event { // GetEventDetails is a testing helper will return the details from the event // payload for a given messageType (request or response) -func GetEventDetails(t testing.TB, e *cloudevents.Event, messageType string) map[string]interface{} { +func GetEventDetails(t testing.TB, e *cloudevents.Event, messageType string) map[string]any { t.Helper() require := require.New(t) require.NotNil(e) require.NotEmpty(messageType) - data, ok := e.Data.(map[string]interface{}) + data, ok := e.Data.(map[string]any) require.Truef(ok, "event was not a map[string]interface") - msgType, ok := data[messageType].(map[string]interface{}) + msgType, ok := data[messageType].(map[string]any) require.Truef(ok, "event data did not contain a %q. Current keys: %q", messageType, reflect.ValueOf(data).MapKeys()) - details, ok := msgType["details"].(map[string]interface{}) + details, ok := msgType["details"].(map[string]any) require.Truef(ok, `%q of event did not contain "details"`, messageType) return details } // AssertRedactedValues will assert that the values for the given keys within // the data have been redacted -func AssertRedactedValues(t testing.TB, data interface{}, keys ...string) { +func AssertRedactedValues(t testing.TB, data any, keys ...string) { t.Helper() assert, require := assert.New(t), require.New(t) require.NotNil(data) - dataMap, ok := data.(map[string]interface{}) + dataMap, ok := data.(map[string]any) require.Truef(ok, "data must be a map[string]interface{}") rMap := make(map[string]bool, len(keys)) @@ -55,7 +55,7 @@ func AssertRedactedValues(t testing.TB, data interface{}, keys ...string) { } for k, v := range dataMap { switch typ := v.(type) { - case []interface{}: + case []any: for _, s := range typ { if _, ok := rMap[k]; ok { assert.Equalf(encrypt.RedactedData, s, "expected %s to be redacted and it was set to: %s", k, v) diff --git a/internal/tests/cluster/util.go b/internal/tests/cluster/util.go index ea06ab535b..a3d382ed19 100644 --- a/internal/tests/cluster/util.go +++ b/internal/tests/cluster/util.go @@ -16,7 +16,7 @@ func expectWorkers(t *testing.T, c *controller.TestController, workers ...*worke for _, w := range workers { workerMap[w.Name()] = w } - updateTimes.Range(func(k, v interface{}) bool { + updateTimes.Range(func(k, v any) bool { require.NotNil(t, k) require.NotNil(t, v) if workerMap[k.(string)] == nil { diff --git a/internal/types/subtypes/attribute_transform_test.go b/internal/types/subtypes/attribute_transform_test.go index b9aa5dafa4..618b5c884a 100644 --- a/internal/types/subtypes/attribute_transform_test.go +++ b/internal/types/subtypes/attribute_transform_test.go @@ -28,9 +28,9 @@ func TestFilterable(t *testing.T) { }, }, func() *structpb.Struct { - w, _ := structpb.NewStruct(map[string]interface{}{ + w, _ := structpb.NewStruct(map[string]any{ "type": "sub_resource", - "attributes": map[string]interface{}{ + "attributes": map[string]any{ "name": "test", }, }) @@ -43,7 +43,7 @@ func TestFilterable(t *testing.T) { Type: "default", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -51,9 +51,9 @@ func TestFilterable(t *testing.T) { }, }, func() *structpb.Struct { - w, _ := structpb.NewStruct(map[string]interface{}{ + w, _ := structpb.NewStruct(map[string]any{ "type": "default", - "attributes": map[string]interface{}{ + "attributes": map[string]any{ "name": "test", }, }) @@ -65,7 +65,7 @@ func TestFilterable(t *testing.T) { &attribute.TestNoOneOf{ Type: "sub_resource", Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -74,7 +74,7 @@ func TestFilterable(t *testing.T) { &attribute.TestNoOneOf{ Type: "sub_resource", Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs diff --git a/internal/types/subtypes/interceptor.go b/internal/types/subtypes/interceptor.go index 2aed2620d7..07bab95968 100644 --- a/internal/types/subtypes/interceptor.go +++ b/internal/types/subtypes/interceptor.go @@ -296,7 +296,7 @@ func transformResponse(msg proto.Message) error { // type:"password" password_attributes:{login_name:"tim"} func AttributeTransformerInterceptor(_ context.Context) grpc.UnaryServerInterceptor { const op = "subtypes.AttributeTransformInterceptor" - return func(interceptorCtx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { + return func(interceptorCtx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { if reqMsg, ok := req.(proto.Message); ok { if err := transformRequest(reqMsg); err != nil { fieldErrs := map[string]string{ diff --git a/internal/types/subtypes/interceptor_ext_test.go b/internal/types/subtypes/interceptor_ext_test.go index 133453556e..8a315fc00f 100644 --- a/internal/types/subtypes/interceptor_ext_test.go +++ b/internal/types/subtypes/interceptor_ext_test.go @@ -16,10 +16,10 @@ import ( func TestAttributeTransformerInterceptor(t *testing.T) { cases := []struct { name string - req interface{} - handlerResp interface{} - expectHandlerReq interface{} - excpetResp interface{} + req any + handlerResp any + expectHandlerReq any + excpetResp any }{ { "TestCreateResource/SubResourceRequest", @@ -28,7 +28,7 @@ func TestAttributeTransformerInterceptor(t *testing.T) { Type: "sub_resource", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -63,7 +63,7 @@ func TestAttributeTransformerInterceptor(t *testing.T) { Type: "sub_resource", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -79,7 +79,7 @@ func TestAttributeTransformerInterceptor(t *testing.T) { OtherId: "trsr_parent", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -116,7 +116,7 @@ func TestAttributeTransformerInterceptor(t *testing.T) { Type: "sub_resource", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -132,7 +132,7 @@ func TestAttributeTransformerInterceptor(t *testing.T) { Item: &attribute.TestResource{ Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -167,7 +167,7 @@ func TestAttributeTransformerInterceptor(t *testing.T) { Type: "sub_resource", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -182,7 +182,7 @@ func TestAttributeTransformerInterceptor(t *testing.T) { Id: "trsr_one", Attrs: &attribute.TestNoItemAttributes_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -193,7 +193,7 @@ func TestAttributeTransformerInterceptor(t *testing.T) { Id: "trsr_one", Attrs: &attribute.TestNoItemAttributes_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -212,7 +212,7 @@ func TestAttributeTransformerInterceptor(t *testing.T) { Id: "trsr_one", Attrs: &attribute.TestNoItemAttributes_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -237,7 +237,7 @@ func TestAttributeTransformerInterceptor(t *testing.T) { Type: "default", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -248,7 +248,7 @@ func TestAttributeTransformerInterceptor(t *testing.T) { Type: "unknown", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -264,7 +264,7 @@ func TestAttributeTransformerInterceptor(t *testing.T) { Type: "sub_resource", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -275,7 +275,7 @@ func TestAttributeTransformerInterceptor(t *testing.T) { Type: "default", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -286,7 +286,7 @@ func TestAttributeTransformerInterceptor(t *testing.T) { Type: "unknown", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -301,7 +301,7 @@ func TestAttributeTransformerInterceptor(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { ctx := context.Background() - handler := func(ctx context.Context, req interface{}) (interface{}, error) { + handler := func(ctx context.Context, req any) (any, error) { require.Empty(t, cmp.Diff(req, tc.expectHandlerReq, protocmp.Transform())) return tc.handlerResp, nil } @@ -316,7 +316,7 @@ func TestAttributeTransformerInterceptor(t *testing.T) { func TestAttributeTransformerInterceptorRequestErrors(t *testing.T) { cases := []struct { name string - req interface{} + req any want error }{ { @@ -326,7 +326,7 @@ func TestAttributeTransformerInterceptorRequestErrors(t *testing.T) { Type: "sub_resource", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "foo": "test", }) return attrs @@ -342,7 +342,7 @@ func TestAttributeTransformerInterceptorRequestErrors(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { ctx := context.Background() - handler := func(ctx context.Context, req interface{}) (interface{}, error) { + handler := func(ctx context.Context, req any) (any, error) { t.Fatalf("handler should not be called") return nil, nil } diff --git a/internal/types/subtypes/interceptor_test.go b/internal/types/subtypes/interceptor_test.go index a6d5dae011..7bf83d3360 100644 --- a/internal/types/subtypes/interceptor_test.go +++ b/internal/types/subtypes/interceptor_test.go @@ -31,7 +31,7 @@ func TestTransformRequestAttributes(t *testing.T) { Type: "sub_resource", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -57,7 +57,7 @@ func TestTransformRequestAttributes(t *testing.T) { Type: "default", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -70,7 +70,7 @@ func TestTransformRequestAttributes(t *testing.T) { Type: "default", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -86,7 +86,7 @@ func TestTransformRequestAttributes(t *testing.T) { Type: "unknown", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -99,7 +99,7 @@ func TestTransformRequestAttributes(t *testing.T) { Type: "unknown", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -115,7 +115,7 @@ func TestTransformRequestAttributes(t *testing.T) { Item: &attribute.TestResource{ Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -141,7 +141,7 @@ func TestTransformRequestAttributes(t *testing.T) { Item: &attribute.TestResource{ Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -154,7 +154,7 @@ func TestTransformRequestAttributes(t *testing.T) { Item: &attribute.TestResource{ Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -170,7 +170,7 @@ func TestTransformRequestAttributes(t *testing.T) { Item: &attribute.TestResource{ Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -183,7 +183,7 @@ func TestTransformRequestAttributes(t *testing.T) { Item: &attribute.TestResource{ Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -229,7 +229,7 @@ func TestTransformRequestAttributes(t *testing.T) { Id: "trsr_one", Attrs: &attribute.TestNoItemAttributes_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -251,7 +251,7 @@ func TestTransformRequestAttributes(t *testing.T) { Item: &attribute.TestNoOneOf{ Type: "sub_resource", Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -262,7 +262,7 @@ func TestTransformRequestAttributes(t *testing.T) { Item: &attribute.TestNoOneOf{ Type: "sub_resource", Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -276,7 +276,7 @@ func TestTransformRequestAttributes(t *testing.T) { Id: "trsr_one", Item: &attribute.TestNoOneOf{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -287,7 +287,7 @@ func TestTransformRequestAttributes(t *testing.T) { Id: "trsr_one", Item: &attribute.TestNoOneOf{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -328,7 +328,7 @@ func TestTransformResponseAttributes(t *testing.T) { Type: "default", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -343,7 +343,7 @@ func TestTransformResponseAttributes(t *testing.T) { Type: "sub_resource", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -354,7 +354,7 @@ func TestTransformResponseAttributes(t *testing.T) { Type: "default", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -383,7 +383,7 @@ func TestTransformResponseAttributes(t *testing.T) { Type: "sub_resource", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -400,7 +400,7 @@ func TestTransformResponseAttributes(t *testing.T) { Type: "plugin", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -414,7 +414,7 @@ func TestTransformResponseAttributes(t *testing.T) { Type: "plugin", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -442,7 +442,7 @@ func TestTransformResponseAttributes(t *testing.T) { Type: "sub_resource", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -470,7 +470,7 @@ func TestTransformResponseAttributes(t *testing.T) { Type: "sub_resource", Attrs: &attribute.TestResource_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -517,7 +517,7 @@ func TestTransformResponseAttributes(t *testing.T) { Id: "trsr_one", Type: "sub_resource", Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -529,7 +529,7 @@ func TestTransformResponseAttributes(t *testing.T) { Id: "trsr_one", Type: "sub_resource", Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -544,7 +544,7 @@ func TestTransformResponseAttributes(t *testing.T) { Id: "trsr_one", Type: "sub_resource", Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -556,7 +556,7 @@ func TestTransformResponseAttributes(t *testing.T) { Id: "trsr_one", Type: "sub_resource", Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -612,7 +612,7 @@ func TestCustomTransformRequest(t *testing.T) { SecondaryId: "secondary_id", Attrs: &attribute.TestCustomTransformation_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs @@ -664,7 +664,7 @@ func TestCustomTransformResponse(t *testing.T) { SecondaryId: "secondary_id", Attrs: &attribute.TestCustomTransformation_Attributes{ Attributes: func() *structpb.Struct { - attrs, _ := structpb.NewStruct(map[string]interface{}{ + attrs, _ := structpb.NewStruct(map[string]any{ "name": "test", }) return attrs diff --git a/internal/types/subtypes/registry.go b/internal/types/subtypes/registry.go index a6a9563576..fa2c78bd4c 100644 --- a/internal/types/subtypes/registry.go +++ b/internal/types/subtypes/registry.go @@ -25,7 +25,7 @@ func (t Subtype) String() string { // prefixes and allows for translating prefixes back to registered subtypes. type Registry struct { subtypesPrefixes map[string]Subtype - knownSubtypes map[Subtype]interface{} + knownSubtypes map[Subtype]any sync.RWMutex } @@ -34,7 +34,7 @@ type Registry struct { func NewRegistry() *Registry { return &Registry{ subtypesPrefixes: make(map[string]Subtype), - knownSubtypes: make(map[Subtype]interface{}), + knownSubtypes: make(map[Subtype]any), } } diff --git a/internal/types/subtypes/registry_global.go b/internal/types/subtypes/registry_global.go index 9c8a1804c0..28a587db21 100644 --- a/internal/types/subtypes/registry_global.go +++ b/internal/types/subtypes/registry_global.go @@ -15,7 +15,7 @@ var globalRegistry = newRegistry() func newRegistry() *registry { return ®istry{ subtypesPrefixes: make(map[string]map[string]Subtype), - knownSubtypes: make(map[string]map[Subtype]interface{}), + knownSubtypes: make(map[string]map[Subtype]any), } } @@ -23,7 +23,7 @@ func newRegistry() *registry { // prefixes and allows for translating prefixes back to registered subtypes. type registry struct { subtypesPrefixes map[string]map[string]Subtype - knownSubtypes map[string]map[Subtype]interface{} + knownSubtypes map[string]map[Subtype]any sync.RWMutex } @@ -97,7 +97,7 @@ func (r *registry) register(ctx context.Context, domain string, subtype Subtype, knownSubtypes, present := r.knownSubtypes[domain] if !present { - knownSubtypes = make(map[Subtype]interface{}) + knownSubtypes = make(map[Subtype]any) r.knownSubtypes[domain] = knownSubtypes r.subtypesPrefixes[domain] = make(map[string]Subtype) } diff --git a/internal/util/is_nil.go b/internal/util/is_nil.go index 62a2c19d8a..c41a982c46 100644 --- a/internal/util/is_nil.go +++ b/internal/util/is_nil.go @@ -3,7 +3,7 @@ package util import "reflect" // IsNil checks if the interface is nil -func IsNil(i interface{}) bool { +func IsNil(i any) bool { if i == nil { return true } diff --git a/internal/util/is_nil_test.go b/internal/util/is_nil_test.go index 2e785eb079..cc70fc3a2b 100644 --- a/internal/util/is_nil_test.go +++ b/internal/util/is_nil_test.go @@ -20,7 +20,7 @@ func Test_IsNil(t *testing.T) { var testChanString chan string tc := []struct { - i interface{} + i any want bool }{ {i: &testError{}, want: false}, diff --git a/plugins/kms/builtin.go b/plugins/kms/builtin.go index 7ea97ad4eb..e6f4a4efc8 100644 --- a/plugins/kms/builtin.go +++ b/plugins/kms/builtin.go @@ -7,7 +7,7 @@ import ( func BuiltinKmsPlugins() map[string]pluginutil.InmemCreationFunc { return map[string]pluginutil.InmemCreationFunc{ - "aead": func() (interface{}, error) { + "aead": func() (any, error) { return aead.NewWrapper(), nil }, } diff --git a/sdk/plugins/host/load.go b/sdk/plugins/host/load.go index ac74473ef5..e7496e1b54 100644 --- a/sdk/plugins/host/load.go +++ b/sdk/plugins/host/load.go @@ -65,7 +65,7 @@ func CreateHostPlugin( return nil, cleanup, err } - var raw interface{} + var raw any switch client := plugClient.(type) { case plugin.ClientProtocol: raw, err = client.Dispense(hostServicePluginSetName) diff --git a/sdk/plugins/host/plugin.go b/sdk/plugins/host/plugin.go index 6b44db321b..28f456401c 100644 --- a/sdk/plugins/host/plugin.go +++ b/sdk/plugins/host/plugin.go @@ -84,6 +84,6 @@ func (h *hostPlugin) GRPCServer(broker *plugin.GRPCBroker, s *grpc.Server) error return nil } -func (h *hostPlugin) GRPCClient(ctx context.Context, broker *plugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error) { +func (h *hostPlugin) GRPCClient(ctx context.Context, broker *plugin.GRPCBroker, c *grpc.ClientConn) (any, error) { return pb.NewHostPluginServiceClient(c), nil } diff --git a/testing/internal/e2e/boundary/boundary.go b/testing/internal/e2e/boundary/boundary.go index f48b2d1d52..183dc6516a 100644 --- a/testing/internal/e2e/boundary/boundary.go +++ b/testing/internal/e2e/boundary/boundary.go @@ -46,7 +46,7 @@ func NewApiClient() (*api.Client, error) { ctx := context.Background() authmethodsClient := authmethods.NewClient(client) authenticationResult, err := authmethodsClient.Authenticate(ctx, c.AuthMethodId, "login", - map[string]interface{}{ + map[string]any{ "login_name": c.AdminLoginName, "password": c.AdminLoginPassword, }, diff --git a/testing/internal/e2e/host/aws/dynamichostcatalog_test.go b/testing/internal/e2e/host/aws/dynamichostcatalog_test.go index 819574b1a8..0c04fdcc78 100644 --- a/testing/internal/e2e/host/aws/dynamichostcatalog_test.go +++ b/testing/internal/e2e/host/aws/dynamichostcatalog_test.go @@ -296,11 +296,11 @@ func TestCreateAwsDynamicHostCatalogApi(t *testing.T) { newHostCatalogResult, err := hcClient.Create(ctx, "plugin", newProjectId, hostcatalogs.WithName("e2e Automated Test Host Catalog"), hostcatalogs.WithPluginName("aws"), - hostcatalogs.WithAttributes(map[string]interface{}{ + hostcatalogs.WithAttributes(map[string]any{ "disable_credential_rotation": true, "region": "us-east-1", }), - hostcatalogs.WithSecrets(map[string]interface{}{ + hostcatalogs.WithSecrets(map[string]any{ "access_key_id": c.AwsAccessKeyId, "secret_access_key": c.AwsSecretAccessKey, }), @@ -312,7 +312,7 @@ func TestCreateAwsDynamicHostCatalogApi(t *testing.T) { // Create a host set and add to catalog hsClient := hostsets.NewClient(client) newHostSetResult, err := hsClient.Create(ctx, newHostCatalogId, - hostsets.WithAttributes(map[string]interface{}{ + hostsets.WithAttributes(map[string]any{ "filters": c.AwsHostSetFilter1, }), hostsets.WithName("e2e Automated Test Host Set"),