diff --git a/.gitignore b/.gitignore index 30dc3d2eb..88cb5d4db 100644 --- a/.gitignore +++ b/.gitignore @@ -128,6 +128,9 @@ update-ui-assets* # Test config file test*.hcl +# Test error files +tmp-errors-Test* + # Enos /enos/**/.enos /enos/terraform-plugin-cache diff --git a/.golangci.yml b/.golangci.yml index 861201607..aff6fcea2 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -21,3 +21,48 @@ issues: - linters: - staticcheck text: "SA1019: out.GrantScopeId is deprecated:" + - linters: + - staticcheck + text: "SA1019: authorized.GetWorkerKeyIdentifiers is deprecated:" + - linters: + - staticcheck + text: "SA1019: result.GetAuthorizedWorkers is deprecated:" + - linters: + - staticcheck + text: "SA1019: item.GetWorkerFilter is deprecated:" + - linters: + - staticcheck + text: "SA1019: out.GetWorkerFilter is deprecated:" + - linters: + - staticcheck + text: "SA1019: out.WorkerFilter is deprecated:" + - linters: + - staticcheck + text: "SA1019: req.GetTokenType is deprecated:" + - linters: + - staticcheck + text: "SA1019: s.resp.GetPkcs8HostKeys is deprecated:" + - linters: + - staticcheck + text: "SA1019: s.resp.GetCredentials is deprecated:" + - linters: + - staticcheck + text: 'SA1019: got.GetAuthorizedWorkers is deprecated:' + - linters: + - staticcheck + text: 'SA1019: gotAuthorizedWorkers.GetWorkerKeyIdentifiers is deprecated:' + - linters: + - staticcheck + text: 'SA1019: tc.want.GetAuthorizedWorkers is deprecated:' + - linters: + - staticcheck + text: 'SA1019: wantAuthorizedWorkers.GetWorkerKeyIdentifiers is deprecated:' + - linters: + - staticcheck + text: "SA1019: authorizedWorkerList.WorkerKeyIdentifiers is deprecated:" + - linters: + - staticcheck + text: "SA1019: req.GetConnectedWorkerKeyIdentifiers is deprecated:" + - linters: + - staticcheck + text: "SA1019: j.GetId is deprecated:" diff --git a/internal/auth/ldap/service_authenticate_test.go b/internal/auth/ldap/service_authenticate_test.go index 9d3a910e9..5803eb6bb 100644 --- a/internal/auth/ldap/service_authenticate_test.go +++ b/internal/auth/ldap/service_authenticate_test.go @@ -7,7 +7,6 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" "os" "sync" "testing" @@ -329,7 +328,7 @@ func TestAuthenticate(t *testing.T) { assert.NotEmpty(got) sinkFileName := c.ObservationEvents.Name() defer func() { _ = os.WriteFile(sinkFileName, nil, 0o666) }() - b, err := ioutil.ReadFile(sinkFileName) + b, err := os.ReadFile(sinkFileName) require.NoError(err) gotRes := &cloudevents.Event{} err = json.Unmarshal(b, gotRes) diff --git a/internal/auth/oidc/account.go b/internal/auth/oidc/account.go index 1d404a2a7..ccd3c9a91 100644 --- a/internal/auth/oidc/account.go +++ b/internal/auth/oidc/account.go @@ -129,14 +129,14 @@ func (a *Account) GetLoginName() string { } // oplog will create oplog metadata for the Account. -func (c *Account) oplog(op oplog.OpType, authMethodScopeId string) oplog.Metadata { +func (a *Account) oplog(op oplog.OpType, authMethodScopeId string) oplog.Metadata { metadata := oplog.Metadata{ - "resource-public-id": []string{c.GetPublicId()}, + "resource-public-id": []string{a.GetPublicId()}, "resource-type": []string{"oidc account"}, "op-type": []string{op.String()}, } - if c.AuthMethodId != "" { - metadata["auth-method-id"] = []string{c.AuthMethodId} + if a.AuthMethodId != "" { + metadata["auth-method-id"] = []string{a.AuthMethodId} } if authMethodScopeId != "" { metadata["scope-id"] = []string{authMethodScopeId} diff --git a/internal/auth/oidc/account_claim_map.go b/internal/auth/oidc/account_claim_map.go index 9b7e23983..83fd0b7e9 100644 --- a/internal/auth/oidc/account_claim_map.go +++ b/internal/auth/oidc/account_claim_map.go @@ -62,14 +62,14 @@ func NewAccountClaimMap(ctx context.Context, authMethodId, fromClaim string, toC } // validate the AccountClaimMap. On success, it will return nil. -func (cs *AccountClaimMap) validate(ctx context.Context, caller errors.Op) error { - if cs.OidcMethodId == "" { +func (s *AccountClaimMap) validate(ctx context.Context, caller errors.Op) error { + if s.OidcMethodId == "" { return errors.New(ctx, errors.InvalidParameter, caller, "missing oidc auth method id") } - if cs.FromClaim == "" { + if s.FromClaim == "" { return errors.New(ctx, errors.InvalidParameter, caller, "missing from claim") } - if _, err := ConvertToAccountToClaim(ctx, cs.ToClaim); err != nil { + if _, err := ConvertToAccountToClaim(ctx, s.ToClaim); err != nil { return errors.Wrap(ctx, err, caller) } return nil @@ -83,8 +83,8 @@ func AllocAccountClaimMap() AccountClaimMap { } // Clone a AccountClaimMap -func (cs *AccountClaimMap) Clone() *AccountClaimMap { - cp := proto.Clone(cs.AccountClaimMap) +func (s *AccountClaimMap) Clone() *AccountClaimMap { + cp := proto.Clone(s.AccountClaimMap) return &AccountClaimMap{ AccountClaimMap: cp.(*store.AccountClaimMap), } diff --git a/internal/auth/oidc/aud_claim.go b/internal/auth/oidc/aud_claim.go index bc569e9c3..a70d1d0af 100644 --- a/internal/auth/oidc/aud_claim.go +++ b/internal/auth/oidc/aud_claim.go @@ -50,11 +50,11 @@ func NewAudClaim(ctx context.Context, authMethodId string, audClaim string) (*Au } // validate the AudClaim. On success, it will return nil. -func (a *AudClaim) validate(ctx context.Context, caller errors.Op) error { - if a.OidcMethodId == "" { +func (c *AudClaim) validate(ctx context.Context, caller errors.Op) error { + if c.OidcMethodId == "" { return errors.New(ctx, errors.InvalidParameter, caller, "missing oidc auth method id") } - if a.Aud == "" { + if c.Aud == "" { return errors.New(ctx, errors.InvalidParameter, caller, "missing aud claim") } return nil diff --git a/internal/auth/oidc/auth_method.go b/internal/auth/oidc/auth_method.go index dd86a29f9..981a9faef 100644 --- a/internal/auth/oidc/auth_method.go +++ b/internal/auth/oidc/auth_method.go @@ -146,24 +146,24 @@ func NewAuthMethod(ctx context.Context, scopeId string, clientId string, clientS // Also, you can't enforce that MaxAge can't equal zero, since the zero value == // NULL in the database and that's what you want if it's unset. A db constraint // will enforce that MaxAge is either -1, NULL or greater than zero. -func (a *AuthMethod) validate(ctx context.Context, caller errors.Op) error { - if a.ScopeId == "" { +func (am *AuthMethod) validate(ctx context.Context, caller errors.Op) error { + if am.ScopeId == "" { return errors.New(ctx, errors.InvalidParameter, caller, "missing scope id") } - if !validState(a.OperationalState) { - return errors.New(ctx, errors.InvalidParameter, caller, fmt.Sprintf("invalid state: %s", a.OperationalState)) + if !validState(am.OperationalState) { + return errors.New(ctx, errors.InvalidParameter, caller, fmt.Sprintf("invalid state: %s", am.OperationalState)) } - if a.Issuer != "" { - if _, err := url.Parse(a.Issuer); err != nil { + if am.Issuer != "" { + if _, err := url.Parse(am.Issuer); err != nil { return errors.New(ctx, errors.InvalidParameter, caller, "not a valid issuer", errors.WithWrap(err)) } } - if a.ApiUrl != "" { - if _, err := url.Parse(a.ApiUrl); err != nil { + if am.ApiUrl != "" { + if _, err := url.Parse(am.ApiUrl); err != nil { return errors.New(ctx, errors.InvalidParameter, caller, "not a valid api url", errors.WithWrap(err)) } } - if a.MaxAge < -1 { + if am.MaxAge < -1 { return errors.New(ctx, errors.InvalidParameter, caller, "max age cannot be less than -1") } return nil @@ -177,76 +177,76 @@ func AllocAuthMethod() AuthMethod { } // Clone an AuthMethod. -func (a *AuthMethod) Clone() *AuthMethod { - cp := proto.Clone(a.AuthMethod) +func (am *AuthMethod) Clone() *AuthMethod { + cp := proto.Clone(am.AuthMethod) return &AuthMethod{ AuthMethod: cp.(*store.AuthMethod), } } // TableName returns the table name. -func (a *AuthMethod) TableName() string { - if a.tableName != "" { - return a.tableName +func (am AuthMethod) TableName() string { + if am.tableName != "" { + return am.tableName } return defaultAuthMethodTableName } // SetTableName sets the table name. -func (a *AuthMethod) SetTableName(n string) { - a.tableName = n +func (am *AuthMethod) SetTableName(n string) { + am.tableName = n } // GetResourceType returns the resource type of the AuthMethod -func (a *AuthMethod) GetResourceType() resource.Type { +func (am AuthMethod) GetResourceType() resource.Type { return resource.AuthMethod } // oplog will create oplog metadata for the AuthMethod. -func (a *AuthMethod) oplog(op oplog.OpType) oplog.Metadata { +func (am *AuthMethod) oplog(op oplog.OpType) oplog.Metadata { metadata := oplog.Metadata{ - "resource-public-id": []string{a.GetPublicId()}, + "resource-public-id": []string{am.GetPublicId()}, "resource-type": []string{"oidc auth method"}, "op-type": []string{op.String()}, - "scope-id": []string{a.ScopeId}, + "scope-id": []string{am.ScopeId}, } return metadata } // encrypt the auth method before writing it to the db -func (a *AuthMethod) encrypt(ctx context.Context, cipher wrapping.Wrapper) error { +func (am *AuthMethod) encrypt(ctx context.Context, cipher wrapping.Wrapper) error { const op = "oidc.(AuthMethod).encrypt" if cipher == nil { return errors.New(ctx, errors.InvalidParameter, op, "missing cipher") } - if err := structwrapping.WrapStruct(ctx, cipher, a.AuthMethod, nil); err != nil { + if err := structwrapping.WrapStruct(ctx, cipher, am.AuthMethod, nil); err != nil { return errors.Wrap(ctx, err, op, errors.WithCode(errors.Encrypt)) } keyId, err := cipher.KeyId(ctx) if err != nil { return errors.Wrap(ctx, err, op, errors.WithCode(errors.Encrypt), errors.WithMsg("failed to read cipher key id")) } - a.KeyId = keyId - if err := a.hmacClientSecret(ctx, cipher); err != nil { + am.KeyId = keyId + if err := am.hmacClientSecret(ctx, cipher); err != nil { return errors.Wrap(ctx, err, op) } return nil } // decrypt the auth method after reading it from the db -func (a *AuthMethod) decrypt(ctx context.Context, cipher wrapping.Wrapper) error { +func (am *AuthMethod) decrypt(ctx context.Context, cipher wrapping.Wrapper) error { const op = "oidc.(AuthMethod).decrypt" if cipher == nil { return errors.New(ctx, errors.InvalidParameter, op, "missing cipher") } - if err := structwrapping.UnwrapStruct(ctx, cipher, a.AuthMethod, nil); err != nil { + if err := structwrapping.UnwrapStruct(ctx, cipher, am.AuthMethod, nil); err != nil { return errors.Wrap(ctx, err, op, errors.WithCode(errors.Decrypt)) } return nil } // hmacClientSecret before writing it to the db -func (a *AuthMethod) hmacClientSecret(ctx context.Context, cipher wrapping.Wrapper) error { +func (am *AuthMethod) hmacClientSecret(ctx context.Context, cipher wrapping.Wrapper) error { const op = "oidc.(AuthMethod).hmacClientSecret" if cipher == nil { return errors.New(ctx, errors.InvalidParameter, op, "missing cipher") @@ -254,11 +254,11 @@ func (a *AuthMethod) hmacClientSecret(ctx context.Context, cipher wrapping.Wrapp // this operation currently uses the legacy WithEd25519 option for hmac'ing. // we should likely deprecate this and introduce a new "crypto version" of // this attribute. - hm, err := crypto.HmacSha256(ctx, []byte(a.ClientSecret), cipher, []byte(a.PublicId), nil, crypto.WithBase64Encoding(), crypto.WithEd25519()) + hm, err := crypto.HmacSha256(ctx, []byte(am.ClientSecret), cipher, []byte(am.PublicId), nil, crypto.WithBase64Encoding(), crypto.WithEd25519()) if err != nil { return errors.Wrap(ctx, err, op, errors.WithCode(errors.Code(errors.Encryption))) } - a.ClientSecretHmac = hm + am.ClientSecretHmac = hm return nil } diff --git a/internal/auth/oidc/claims_scope.go b/internal/auth/oidc/claims_scope.go index fa59cb59c..6f905547f 100644 --- a/internal/auth/oidc/claims_scope.go +++ b/internal/auth/oidc/claims_scope.go @@ -42,14 +42,14 @@ func NewClaimsScope(ctx context.Context, authMethodId, claimsScope string) (*Cla } // validate the ClaimsScope. On success, it will return nil. -func (cs *ClaimsScope) validate(ctx context.Context, caller errors.Op) error { - if cs.OidcMethodId == "" { +func (s *ClaimsScope) validate(ctx context.Context, caller errors.Op) error { + if s.OidcMethodId == "" { return errors.New(ctx, errors.InvalidParameter, caller, "missing oidc auth method id") } - if cs.Scope == "" { + if s.Scope == "" { return errors.New(ctx, errors.InvalidParameter, caller, "missing claims scope") } - if cs.Scope == DefaultClaimsScope { + if s.Scope == DefaultClaimsScope { return errors.New(ctx, errors.InvalidParameter, caller, "openid is the default scope and cannot be added as optional") } return nil @@ -63,8 +63,8 @@ func AllocClaimsScope() ClaimsScope { } // Clone a ClaimsScope -func (cs *ClaimsScope) Clone() *ClaimsScope { - cp := proto.Clone(cs.ClaimsScope) +func (s *ClaimsScope) Clone() *ClaimsScope { + cp := proto.Clone(s.ClaimsScope) return &ClaimsScope{ ClaimsScope: cp.(*store.ClaimsScope), } diff --git a/internal/auth/oidc/service_callback.go b/internal/auth/oidc/service_callback.go index 2c711d021..505c252ae 100644 --- a/internal/auth/oidc/service_callback.go +++ b/internal/auth/oidc/service_callback.go @@ -9,7 +9,6 @@ import ( "strings" "time" - "github.com/golang/protobuf/proto" "github.com/hashicorp/boundary/internal/auth/oidc/request" "github.com/hashicorp/boundary/internal/authtoken" "github.com/hashicorp/boundary/internal/errors" @@ -17,6 +16,7 @@ import ( "github.com/hashicorp/cap/oidc" "github.com/hashicorp/go-bexpr" "github.com/mitchellh/pointerstructure" + "google.golang.org/protobuf/proto" ) // Callback is an oidc domain service function for processing a successful OIDC diff --git a/internal/auth/oidc/service_callback_test.go b/internal/auth/oidc/service_callback_test.go index 1e7ea322d..e5b088aea 100644 --- a/internal/auth/oidc/service_callback_test.go +++ b/internal/auth/oidc/service_callback_test.go @@ -7,7 +7,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "net/url" @@ -382,7 +382,7 @@ func Test_Callback(t *testing.T) { sinkFileName := c.ObservationEvents.Name() defer func() { _ = os.WriteFile(sinkFileName, nil, 0o666) }() - b, err := ioutil.ReadFile(sinkFileName) + b, err := os.ReadFile(sinkFileName) require.NoError(err) got := &cloudevents.Event{} err = json.Unmarshal(b, got) @@ -632,7 +632,7 @@ func Test_StartAuth_to_Callback(t *testing.T) { resp, err := client.Get(authUrl.String()) require.NoError(err) defer resp.Body.Close() - contents, err := ioutil.ReadAll(resp.Body) + contents, err := io.ReadAll(resp.Body) require.NoError(err) require.Containsf(string(contents), "Congratulations", "expected \"Congratulations\" on successful oidc authentication and got: %s", string(contents)) @@ -847,7 +847,7 @@ func Test_ManagedGroupFiltering(t *testing.T) { require.NoError(err) sinkFileName := c.ObservationEvents.Name() defer func() { _ = os.WriteFile(sinkFileName, nil, 0o666) }() - b, err := ioutil.ReadFile(sinkFileName) + b, err := os.ReadFile(sinkFileName) require.NoError(err) got := &cloudevents.Event{} err = json.Unmarshal(b, got) diff --git a/internal/auth/oidc/service_token_request_test.go b/internal/auth/oidc/service_token_request_test.go index 6f30f895c..552a26367 100644 --- a/internal/auth/oidc/service_token_request_test.go +++ b/internal/auth/oidc/service_token_request_test.go @@ -9,7 +9,6 @@ import ( "testing" "time" - "github.com/golang/protobuf/proto" "github.com/hashicorp/boundary/internal/auth/oidc/request" "github.com/hashicorp/boundary/internal/authtoken" "github.com/hashicorp/boundary/internal/db" @@ -21,6 +20,7 @@ import ( "github.com/mr-tron/base58" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" ) @@ -188,6 +188,7 @@ func Test_TokenRequest(t *testing.T) { blobInfo, err := testRequestWrapper.Encrypt(ctx, []byte("not-valid-request-token"), wrapping.WithAad([]byte(fmt.Sprintf("%s%s", testAuthMethod.PublicId, testAuthMethod.ScopeId)))) require.NoError(t, err) marshaledBlob, err := proto.Marshal(blobInfo) + require.NoError(t, err) keyId, err := testRequestWrapper.KeyId(ctx) require.NoError(t, err) w := request.Wrapper{ @@ -220,6 +221,7 @@ func Test_TokenRequest(t *testing.T) { blobInfo, err := testRequestWrapper.Encrypt(ctx, marshaledReqTk, wrapping.WithAad([]byte(fmt.Sprintf("%s%s", testAuthMethod.PublicId, testAuthMethod.ScopeId)))) require.NoError(t, err) marshaledBlob, err := proto.Marshal(blobInfo) + require.NoError(t, err) keyId, err := testRequestWrapper.KeyId(ctx) require.NoError(t, err) w := request.Wrapper{ @@ -251,6 +253,7 @@ func Test_TokenRequest(t *testing.T) { blobInfo, err := testRequestWrapper.Encrypt(ctx, marshaledReqTk, wrapping.WithAad([]byte(fmt.Sprintf("%s%s", testAuthMethod.PublicId, testAuthMethod.ScopeId)))) require.NoError(t, err) marshaledBlob, err := proto.Marshal(blobInfo) + require.NoError(t, err) keyId, err := testRequestWrapper.KeyId(ctx) require.NoError(t, err) w := request.Wrapper{ @@ -283,6 +286,7 @@ func Test_TokenRequest(t *testing.T) { blobInfo, err := testRequestWrapper.Encrypt(ctx, marshaledReqTk, wrapping.WithAad([]byte(fmt.Sprintf("%s%s", testAuthMethod.PublicId, testAuthMethod.ScopeId)))) require.NoError(t, err) marshaledBlob, err := proto.Marshal(blobInfo) + require.NoError(t, err) keyId, err := testRequestWrapper.KeyId(ctx) require.NoError(t, err) w := request.Wrapper{ diff --git a/internal/auth/oidc/testing.go b/internal/auth/oidc/testing.go index fa4e2d33a..be4e924d3 100644 --- a/internal/auth/oidc/testing.go +++ b/internal/auth/oidc/testing.go @@ -12,7 +12,7 @@ import ( "crypto/x509/pkix" "encoding/pem" "fmt" - "io/ioutil" + "io" "log" "math/big" "net" @@ -431,7 +431,7 @@ func startTestControllerSrv(t testing.TB, oidcRepoFn OidcRepoFactory, iamRepoFn atRepoFn: atRepoFn, } s.httpServer = httptest.NewServer(s) - s.httpServer.Config.ErrorLog = log.New(ioutil.Discard, "", 0) + s.httpServer.Config.ErrorLog = log.New(io.Discard, "", 0) s.t.Cleanup(s.Stop) return s } @@ -492,7 +492,7 @@ func (s *testControllerSrv) ServeHTTP(w http.ResponseWriter, req *http.Request) case error != "": errorRedirectTo := fmt.Sprintf("%s/%s?error=%s", s.Addr(), AuthenticationErrorsEndpoint, error) s.t.Log("auth error: ", errorRedirectTo) - http.RedirectHandler(errorRedirectTo, 301) + http.RedirectHandler(errorRedirectTo, http.StatusMovedPermanently) default: redirectTo, err := Callback(context.Background(), s.oidcRepoFn, @@ -505,7 +505,7 @@ func (s *testControllerSrv) ServeHTTP(w http.ResponseWriter, req *http.Request) if err != nil { errorRedirectTo := fmt.Sprintf("%s/%s?error=%s", s.Addr(), AuthenticationErrorsEndpoint, url.QueryEscape(err.Error())) s.t.Log("callback error: ", errorRedirectTo) - http.RedirectHandler(errorRedirectTo, 302) + http.RedirectHandler(errorRedirectTo, http.StatusFound) return } s.t.Log("callback success: ", redirectTo) diff --git a/internal/authtoken/authtoken_test.go b/internal/authtoken/authtoken_test.go index debefc7bc..dc6513362 100644 --- a/internal/authtoken/authtoken_test.go +++ b/internal/authtoken/authtoken_test.go @@ -8,7 +8,6 @@ import ( "testing" "time" - "github.com/golang/protobuf/ptypes" "github.com/hashicorp/boundary/internal/auth/password" "github.com/hashicorp/boundary/internal/authtoken/store" "github.com/hashicorp/boundary/internal/db" @@ -18,6 +17,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" ) // This file contains tests for methods defined in authtoken.go as well as tests which exercise the db @@ -43,8 +43,7 @@ func TestAuthToken_DbUpdate(t *testing.T) { nullMask []string authTok *store.AuthToken } - future, err := ptypes.TimestampProto(time.Now().Add(time.Hour)) - require.NoError(t, err) + future := timestamppb.New(time.Now().Add(time.Hour)) tests := []struct { name string diff --git a/internal/authtoken/repository.go b/internal/authtoken/repository.go index f06273065..56b3bd07d 100644 --- a/internal/authtoken/repository.go +++ b/internal/authtoken/repository.go @@ -9,12 +9,12 @@ import ( "fmt" "time" - "github.com/golang/protobuf/ptypes" "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/db/timestamp" "github.com/hashicorp/boundary/internal/errors" "github.com/hashicorp/boundary/internal/iam" "github.com/hashicorp/boundary/internal/kms" + "google.golang.org/protobuf/types/known/timestamppb" ) var ( @@ -104,10 +104,7 @@ func (r *Repository) CreateAuthToken(ctx context.Context, withIamUser *iam.User, // We truncate the expiration time to the nearest second to make testing in different platforms with // different time resolutions easier. - expiration, err := ptypes.TimestampProto(time.Now().Add(r.timeToLiveDuration).Truncate(time.Second)) - if err != nil { - return nil, errors.Wrap(ctx, err, op, errors.WithCode(errors.InvalidTimeStamp)) - } + expiration := timestamppb.New(time.Now().Add(r.timeToLiveDuration).Truncate(time.Second)) at.ExpirationTime = ×tamp.Timestamp{Timestamp: expiration} var newAuthToken *AuthToken @@ -215,14 +212,8 @@ func (r *Repository) ValidateToken(ctx context.Context, id, token string, opt .. } // If the token is too old or stale invalidate it and return nothing. - exp, err := ptypes.Timestamp(retAT.GetExpirationTime().GetTimestamp()) - if err != nil { - return nil, errors.Wrap(ctx, err, op, errors.WithMsg("expiration time"), errors.WithCode(errors.InvalidTimeStamp)) - } - lastAccessed, err := ptypes.Timestamp(retAT.GetApproximateLastAccessTime().GetTimestamp()) - if err != nil { - return nil, errors.Wrap(ctx, err, op, errors.WithMsg("last accessed time"), errors.WithCode(errors.InvalidTimeStamp)) - } + exp := retAT.GetExpirationTime().AsTime() + lastAccessed := retAT.GetApproximateLastAccessTime().AsTime() now := time.Now() sinceLastAccessed := now.Sub(lastAccessed) + timeSkew diff --git a/internal/authtoken/repository_test.go b/internal/authtoken/repository_test.go index b74b5e2c5..fe08d6eff 100644 --- a/internal/authtoken/repository_test.go +++ b/internal/authtoken/repository_test.go @@ -9,7 +9,6 @@ import ( "testing" "time" - "github.com/golang/protobuf/ptypes" "github.com/google/go-cmp/cmp" "github.com/hashicorp/boundary/globals" "github.com/hashicorp/boundary/internal/auth/password" @@ -19,6 +18,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/testing/protocmp" + "google.golang.org/protobuf/types/known/timestamppb" "github.com/hashicorp/boundary/internal/authtoken/store" "github.com/hashicorp/boundary/internal/db" @@ -365,10 +365,8 @@ func TestRepository_LookupAuthToken(t *testing.T) { // is because the resolution of the timestamp in the db does not // match the resolution in Go code. But might be worth checking // into. - wantGoTimeExpr, err := ptypes.Timestamp(tt.want.AuthToken.GetExpirationTime().Timestamp) - require.NoError(err) - gotGoTimeExpr, err := ptypes.Timestamp(got.AuthToken.GetExpirationTime().Timestamp) - require.NoError(err) + wantGoTimeExpr := tt.want.AuthToken.GetExpirationTime().Timestamp.AsTime() + gotGoTimeExpr := got.AuthToken.GetExpirationTime().Timestamp.AsTime() assert.WithinDuration(wantGoTimeExpr, gotGoTimeExpr, time.Millisecond) tt.want.AuthToken.ExpirationTime = got.AuthToken.ExpirationTime assert.Empty(cmp.Diff(tt.want.AuthToken, got.AuthToken, protocmp.Transform())) @@ -397,8 +395,7 @@ func TestRepository_ValidateToken(t *testing.T) { at.Token = "" at.CtToken = nil at.KeyId = "" - atTime, err := ptypes.Timestamp(at.GetApproximateLastAccessTime().GetTimestamp()) - require.NoError(t, err) + atTime := at.GetApproximateLastAccessTime() require.NotNil(t, atTime) badId, err := NewAuthTokenId(ctx) @@ -465,18 +462,16 @@ func TestRepository_ValidateToken(t *testing.T) { require.NotNil(tt.want, "Got %v but wanted nil", got) // NOTE: See comment in LookupAuthToken about this logic - wantGoTimeExpr, err := ptypes.Timestamp(tt.want.AuthToken.GetExpirationTime().Timestamp) - require.NoError(err) - gotGoTimeExpr, err := ptypes.Timestamp(got.AuthToken.GetExpirationTime().Timestamp) - require.NoError(err) + wantGoTimeExpr := tt.want.AuthToken.GetExpirationTime().AsTime() + gotGoTimeExpr := got.AuthToken.GetExpirationTime().AsTime() assert.WithinDuration(wantGoTimeExpr, gotGoTimeExpr, time.Millisecond) tt.want.AuthToken.ExpirationTime = got.AuthToken.ExpirationTime assert.Empty(cmp.Diff(tt.want.AuthToken, got.AuthToken, protocmp.Transform())) // preTime1 should be the value prior to the ValidateToken was called so it should equal creation time - preTime1, err := ptypes.Timestamp(got.GetApproximateLastAccessTime().GetTimestamp()) + preTime1 := got.GetApproximateLastAccessTime() require.NoError(err) - assert.True(preTime1.Equal(atTime), "Create time %q doesn't match the time from the first call to MaybeUpdateLastAccesssed: %q.", atTime, preTime1) + assert.True(preTime1.AsTime().Equal(atTime.AsTime()), "Create time %q doesn't match the time from the first call to MaybeUpdateLastAccesssed: %q.", atTime, preTime1) // Enable the duration which limits how frequently a token's approximate last accessed time can be updated // so the next call doesn't cause the last accessed time to be updated. @@ -484,18 +479,16 @@ func TestRepository_ValidateToken(t *testing.T) { got2, err := repo.ValidateToken(ctx, tt.id, tt.token) assert.NoError(err) - preTime2, err := ptypes.Timestamp(got2.GetApproximateLastAccessTime().GetTimestamp()) - require.NoError(err) - assert.True(preTime2.After(preTime1), "First updated time %q was not after the creation time %q", preTime2, preTime1) + preTime2 := got2.GetApproximateLastAccessTime().GetTimestamp() + assert.True(preTime2.AsTime().After(preTime1.AsTime()), "First updated time %q was not after the creation time %q", preTime2, preTime1) // We should find no oplog since tokens are not replicated, so they don't need oplog entries. assert.Error(db.TestVerifyOplog(t, rw, got.GetPublicId(), db.WithOperation(oplog.OpType_OP_TYPE_UPDATE))) got3, err := repo.ValidateToken(ctx, tt.id, tt.token) require.NoError(err) - preTime3, err := ptypes.Timestamp(got3.GetApproximateLastAccessTime().GetTimestamp()) - require.NoError(err) - assert.True(preTime3.Equal(preTime2), "The 3rd timestamp %q was not equal to the second time %q", preTime3, preTime2) + preTime3 := got3.GetApproximateLastAccessTime() + assert.True(preTime3.AsTime().Equal(preTime2.AsTime()), "The 3rd timestamp %q was not equal to the second time %q", preTime3, preTime2) }) } } @@ -880,11 +873,9 @@ func Test_IssuePendingToken(t *testing.T) { } require.NoError(err) assert.NotEmpty(tk) - accessTime, err := ptypes.Timestamp(tk.GetApproximateLastAccessTime().GetTimestamp()) - require.NoError(err) - createTime, err := ptypes.Timestamp(tk.GetCreateTime().GetTimestamp()) - require.NoError(err) - assert.True(accessTime.After(createTime), "last access time %q was not after the creation time %q", accessTime, createTime) + accessTime := tk.GetApproximateLastAccessTime() + createTime := tk.GetCreateTime().GetTimestamp() + assert.True(accessTime.AsTime().After(createTime.AsTime()), "last access time %q was not after the creation time %q", accessTime, createTime) }) } } @@ -913,8 +904,7 @@ func Test_CloseExpiredPendingTokens(t *testing.T) { id, err := NewAuthTokenId(ctx) require.NoError(t, err) at.PublicId = id - exp, err := ptypes.TimestampProto(time.Now().Add(expIn).Truncate(time.Second)) - require.NoError(t, err) + exp := timestamppb.New(time.Now().Add(expIn).Truncate(time.Second)) at.ExpirationTime = ×tamp.Timestamp{Timestamp: exp} at.Status = string(status) at.AuthAccountId = accts[i].PublicId diff --git a/internal/bsr/bsr_open_test.go b/internal/bsr/bsr_open_test.go index b2716d144..5c79a8ffe 100644 --- a/internal/bsr/bsr_open_test.go +++ b/internal/bsr/bsr_open_test.go @@ -112,10 +112,10 @@ func TestOpenBSRMethods(t *testing.T) { require.NoError(t, err) require.NotNil(t, sesh) - sesh.EncodeSummary(ctx, &BaseChannelSummary{ + require.NoError(t, sesh.EncodeSummary(ctx, &BaseChannelSummary{ Id: "TEST_CHANNEL_ID", ConnectionRecordingId: "TEST_CONNECTION_RECORDING_ID", - }) + })) connectionId := "connection" connMeta := &ConnectionRecordingMeta{Id: connectionId} @@ -123,10 +123,10 @@ func TestOpenBSRMethods(t *testing.T) { require.NoError(t, err) require.NotNil(t, conn) - conn.EncodeSummary(ctx, &BaseConnectionSummary{ + require.NoError(t, conn.EncodeSummary(ctx, &BaseConnectionSummary{ Id: "TEST_CONNECTION_ID", ChannelCount: 1, - }) + })) channelId := "channel" chanMeta := &ChannelRecordingMeta{ @@ -137,10 +137,10 @@ func TestOpenBSRMethods(t *testing.T) { require.NoError(t, err) require.NotNil(t, ch) - ch.EncodeSummary(ctx, &BaseSessionSummary{ + require.NoError(t, ch.EncodeSummary(ctx, &BaseSessionSummary{ Id: "TEST_SESSION_ID", ConnectionCount: 1, - }) + })) ch.Close(ctx) conn.Close(ctx) @@ -424,9 +424,9 @@ func TestOpenBSRMethods_WithoutSummaryAllocFunc(t *testing.T) { require.NoError(t, err) require.NotNil(t, ch) - sesh.EncodeSummary(ctx, tc.sessionAllocFunc) - conn.EncodeSummary(ctx, tc.connectionAllocFunc) - ch.EncodeSummary(ctx, tc.channelAllocFunc) + require.NoError(t, sesh.EncodeSummary(ctx, tc.sessionAllocFunc)) + require.NoError(t, conn.EncodeSummary(ctx, tc.connectionAllocFunc)) + require.NoError(t, ch.EncodeSummary(ctx, tc.channelAllocFunc)) ch.Close(ctx) conn.Close(ctx) @@ -509,20 +509,20 @@ func TestCloseBSRMethods(t *testing.T) { require.NoError(t, err) require.NotNil(t, sesh) - sesh.EncodeSummary(ctx, &BaseChannelSummary{ + require.NoError(t, sesh.EncodeSummary(ctx, &BaseChannelSummary{ Id: "TEST_CHANNEL_ID", ConnectionRecordingId: "TEST_CONNECTION_RECORDING_ID", - }) + })) connMeta := &ConnectionRecordingMeta{Id: connectionId} conn, err := sesh.NewConnection(ctx, connMeta) require.NoError(t, err) require.NotNil(t, conn) - conn.EncodeSummary(ctx, &BaseConnectionSummary{ + require.NoError(t, conn.EncodeSummary(ctx, &BaseConnectionSummary{ Id: "TEST_CONNECTION_ID", ChannelCount: 1, - }) + })) chanMeta := &ChannelRecordingMeta{ Id: channelId, @@ -532,10 +532,10 @@ func TestCloseBSRMethods(t *testing.T) { require.NoError(t, err) require.NotNil(t, ch) - ch.EncodeSummary(ctx, &BaseSessionSummary{ + require.NoError(t, ch.EncodeSummary(ctx, &BaseSessionSummary{ Id: "TEST_SESSION_ID", ConnectionCount: 1, - }) + })) ch.Close(ctx) conn.Close(ctx) diff --git a/internal/cmd/base/base.go b/internal/cmd/base/base.go index e4ecaee5a..c59836aac 100644 --- a/internal/cmd/base/base.go +++ b/internal/cmd/base/base.go @@ -10,7 +10,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "os" "os/signal" "regexp" @@ -517,7 +516,7 @@ func NewFlagSets(ui cli.Ui) *FlagSets { // Errors and usage are controlled by the CLI. mainSet.Usage = func() {} - mainSet.SetOutput(ioutil.Discard) + mainSet.SetOutput(io.Discard) return &FlagSets{ flagSets: make([]*FlagSet, 0, 6), @@ -528,41 +527,41 @@ func NewFlagSets(ui cli.Ui) *FlagSets { } // NewFlagSet creates a new flag set from the given flag sets. -func (f *FlagSets) NewFlagSet(name string) *FlagSet { +func (fs *FlagSets) NewFlagSet(name string) *FlagSet { flagSet := NewFlagSet(name) - flagSet.mainSet = f.mainSet - flagSet.completions = f.completions - f.flagSets = append(f.flagSets, flagSet) + flagSet.mainSet = fs.mainSet + flagSet.completions = fs.completions + fs.flagSets = append(fs.flagSets, flagSet) return flagSet } // Completions returns the completions for this flag set. -func (f *FlagSets) Completions() complete.Flags { - if f == nil { +func (fs *FlagSets) Completions() complete.Flags { + if fs == nil { return nil } - return f.completions + return fs.completions } // Parse parses the given flags, returning any errors. -func (f *FlagSets) Parse(args []string) error { - return f.mainSet.Parse(args) +func (fs *FlagSets) Parse(args []string) error { + return fs.mainSet.Parse(args) } // Parsed reports whether the command-line flags have been parsed. -func (f *FlagSets) Parsed() bool { - return f.mainSet.Parsed() +func (fs *FlagSets) Parsed() bool { + return fs.mainSet.Parsed() } // Args returns the remaining args after parsing. -func (f *FlagSets) Args() []string { - return f.mainSet.Args() +func (fs *FlagSets) Args() []string { + return fs.mainSet.Args() } // Visit visits the flags in lexicographical order, calling fn for each. It // visits only those flags that have been set. -func (f *FlagSets) Visit(fn func(*flag.Flag)) { - f.mainSet.Visit(fn) +func (fs *FlagSets) Visit(fn func(*flag.Flag)) { + fs.mainSet.Visit(fn) } // Help builds custom help for this command, grouping by flag set. diff --git a/internal/cmd/base/dev.go b/internal/cmd/base/dev.go index 512573788..92404c03e 100644 --- a/internal/cmd/base/dev.go +++ b/internal/cmd/base/dev.go @@ -683,11 +683,11 @@ func (l *oidcLogger) Infof(format string, args ...any) { } // FailNow will panic (as required by the interface it's implementing) -func (_ *oidcLogger) FailNow() { +func (*oidcLogger) FailNow() { panic("sys eventer failed, see logs for output (if any)") } -func (_ *oidcLogger) caller() event.Op { +func (*oidcLogger) caller() event.Op { var caller event.Op pc, _, _, ok := runtime.Caller(2) details := runtime.FuncForPC(pc) diff --git a/internal/cmd/base/dev_test.go b/internal/cmd/base/dev_test.go index 9a2842c8f..1f0e0fb60 100644 --- a/internal/cmd/base/dev_test.go +++ b/internal/cmd/base/dev_test.go @@ -6,7 +6,6 @@ package base import ( "encoding/json" "fmt" - "io/ioutil" "os" "sync" "testing" @@ -52,7 +51,7 @@ func Test_oidcLogger_Errorf(t *testing.T) { l.Errorf(tt.fmt, tt.args...) sinkFileName := c.AllEvents.Name() defer func() { _ = os.WriteFile(sinkFileName, nil, 0o666) }() - b, err := ioutil.ReadFile(sinkFileName) + b, err := os.ReadFile(sinkFileName) require.NoError(err) gotEvent := &cloudevents.Event{} err = json.Unmarshal(b, gotEvent) @@ -98,7 +97,7 @@ func Test_oidcLogger_Infof(t *testing.T) { l.Infof(tt.fmt, tt.args...) sinkFileName := c.AllEvents.Name() defer func() { _ = os.WriteFile(sinkFileName, nil, 0o666) }() - b, err := ioutil.ReadFile(sinkFileName) + b, err := os.ReadFile(sinkFileName) require.NoError(err) gotEvent := &cloudevents.Event{} err = json.Unmarshal(b, gotEvent) diff --git a/internal/cmd/base/flags.go b/internal/cmd/base/flags.go index 72fb100dc..6ea416c47 100644 --- a/internal/cmd/base/flags.go +++ b/internal/cmd/base/flags.go @@ -830,10 +830,10 @@ func sliceMapToKV(m map[string][]string) string { return strings.Join(list, ", ") } -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 } +func (s *stringSliceMapValue) Get() any { return *s.target } +func (s *stringSliceMapValue) String() string { return sliceMapToKV(*s.target) } +func (s *stringSliceMapValue) Example() string { return "key1=val-a, key2=val-b,val-c" } +func (s *stringSliceMapValue) Hidden() bool { return s.hidden } // -- VarFlag type VarFlag struct { diff --git a/internal/cmd/base/logging.go b/internal/cmd/base/logging.go index 7b9486e38..b470ae3a9 100644 --- a/internal/cmd/base/logging.go +++ b/internal/cmd/base/logging.go @@ -79,20 +79,60 @@ func (g *GRPCLogFaker) Fatalln(args ...any) { os.Exit(1) } -func (g *GRPCLogFaker) Print(args ...any) { +func (g *GRPCLogFaker) Info(args ...any) { if g.Log && g.Logger.IsDebug() { g.Logger.Debug(fmt.Sprint(args...)) } } -func (g *GRPCLogFaker) Printf(format string, args ...any) { +func (g *GRPCLogFaker) Infof(format string, args ...any) { if g.Log && g.Logger.IsDebug() { g.Logger.Debug(fmt.Sprintf(format, args...)) } } -func (g *GRPCLogFaker) Println(args ...any) { +func (g *GRPCLogFaker) Infoln(args ...any) { if g.Log && g.Logger.IsDebug() { g.Logger.Debug(fmt.Sprintln(args...)) } } + +func (g *GRPCLogFaker) Warning(args ...any) { + if g.Log && g.Logger.IsDebug() { + g.Logger.Debug(fmt.Sprint(args...)) + } +} + +func (g *GRPCLogFaker) Warningf(format string, args ...any) { + if g.Log && g.Logger.IsDebug() { + g.Logger.Debug(fmt.Sprintf(format, args...)) + } +} + +func (g *GRPCLogFaker) Warningln(args ...any) { + if g.Log && g.Logger.IsDebug() { + g.Logger.Debug(fmt.Sprintln(args...)) + } +} + +func (g *GRPCLogFaker) Error(args ...any) { + if g.Log && g.Logger.IsDebug() { + g.Logger.Debug(fmt.Sprint(args...)) + } +} + +func (g *GRPCLogFaker) Errorf(format string, args ...any) { + if g.Log && g.Logger.IsDebug() { + g.Logger.Debug(fmt.Sprintf(format, args...)) + } +} + +func (g *GRPCLogFaker) Errorln(args ...any) { + if g.Log && g.Logger.IsDebug() { + g.Logger.Debug(fmt.Sprintln(args...)) + } +} + +func (g *GRPCLogFaker) V(l int) bool { + return true +} diff --git a/internal/cmd/base/servers.go b/internal/cmd/base/servers.go index 8824f9e52..2cac17276 100644 --- a/internal/cmd/base/servers.go +++ b/internal/cmd/base/servers.go @@ -48,6 +48,8 @@ import ( "github.com/hashicorp/go-secure-stdlib/strutil" "github.com/mitchellh/cli" "github.com/prometheus/client_golang/prometheus" + "golang.org/x/text/cases" + "golang.org/x/text/language" "google.golang.org/grpc/grpclog" ) @@ -283,7 +285,7 @@ func (b *Server) SetupLogging(flagLogLevel, flagLogFormat, configLogLevel, confi // create GRPC logger namedGRPCLogFaker := b.Logger.Named("grpclogfaker") - grpclog.SetLogger(&GRPCLogFaker{ + grpclog.SetLoggerV2(&GRPCLogFaker{ Logger: namedGRPCLogFaker, Log: os.Getenv("BOUNDARY_GRPC_LOGGING") != "", }) @@ -411,7 +413,7 @@ func (b *Server) PrintInfo(ui cli.Ui) { ui.Output(fmt.Sprintf( "%s%s: %s", strings.Repeat(" ", padding-len(k)), - strings.Title(k), + cases.Title(language.AmericanEnglish).String(k), b.Info[k])) } ui.Output("") diff --git a/internal/cmd/commands/accountscmd/oidc_funcs.go b/internal/cmd/commands/accountscmd/oidc_funcs.go index 5e1f03638..a1480577d 100644 --- a/internal/cmd/commands/accountscmd/oidc_funcs.go +++ b/internal/cmd/commands/accountscmd/oidc_funcs.go @@ -58,8 +58,8 @@ func (c *OidcCommand) extraOidcHelpFunc(helpMap map[string]func() string) string return helpStr + c.Flags().Help() } -func extraOidcFlagsFuncImpl(c *OidcCommand, set *base.FlagSets, f *base.FlagSet) { - f = set.NewFlagSet("Oidc Account Options") +func extraOidcFlagsFuncImpl(c *OidcCommand, set *base.FlagSets, _ *base.FlagSet) { + f := set.NewFlagSet("Oidc Account Options") for _, name := range flagsOidcMap[c.Func] { switch name { diff --git a/internal/cmd/commands/accountscmd/password_funcs.go b/internal/cmd/commands/accountscmd/password_funcs.go index 14c0dafa6..9728c25af 100644 --- a/internal/cmd/commands/accountscmd/password_funcs.go +++ b/internal/cmd/commands/accountscmd/password_funcs.go @@ -62,8 +62,8 @@ func (c *PasswordCommand) extraPasswordHelpFunc(helpMap map[string]func() string return helpStr + c.Flags().Help() } -func extraPasswordFlagsFuncImpl(c *PasswordCommand, set *base.FlagSets, f *base.FlagSet) { - f = set.NewFlagSet("Password Account Options") +func extraPasswordFlagsFuncImpl(c *PasswordCommand, set *base.FlagSets, _ *base.FlagSet) { + f := set.NewFlagSet("Password Account Options") for _, name := range flagsPasswordMap[c.Func] { switch name { diff --git a/internal/cmd/commands/authmethodscmd/password_funcs.go b/internal/cmd/commands/authmethodscmd/password_funcs.go index 9ce3247ed..377e8dcf4 100644 --- a/internal/cmd/commands/authmethodscmd/password_funcs.go +++ b/internal/cmd/commands/authmethodscmd/password_funcs.go @@ -57,8 +57,8 @@ func (c *PasswordCommand) extraPasswordHelpFunc(helpMap map[string]func() string return helpStr + c.Flags().Help() } -func extraPasswordFlagsFuncImpl(c *PasswordCommand, set *base.FlagSets, f *base.FlagSet) { - f = set.NewFlagSet("Password Auth Method Options") +func extraPasswordFlagsFuncImpl(c *PasswordCommand, set *base.FlagSets, _ *base.FlagSet) { + f := set.NewFlagSet("Password Auth Method Options") for _, name := range flagsPasswordMap[c.Func] { switch name { diff --git a/internal/cmd/commands/config/encryptdecrypt.go b/internal/cmd/commands/config/encryptdecrypt.go index 1f7fd642e..01129270d 100644 --- a/internal/cmd/commands/config/encryptdecrypt.go +++ b/internal/cmd/commands/config/encryptdecrypt.go @@ -7,7 +7,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "net/textproto" "os" "strings" @@ -195,7 +194,7 @@ func (c *EncryptDecryptCommand) Run(args []string) (ret int) { }() } - d, err := ioutil.ReadFile(c.flagConfig) + d, err := os.ReadFile(c.flagConfig) if err != nil { c.UI.Error(fmt.Errorf("Error reading config file: %w", err).Error()) return base.CommandUserError diff --git a/internal/cmd/commands/config/encryptdecrypt_test.go b/internal/cmd/commands/config/encryptdecrypt_test.go index 9a47937d1..8d237eee4 100644 --- a/internal/cmd/commands/config/encryptdecrypt_test.go +++ b/internal/cmd/commands/config/encryptdecrypt_test.go @@ -7,7 +7,6 @@ import ( "bufio" "bytes" "fmt" - "io/ioutil" "os" "strings" "testing" @@ -96,7 +95,7 @@ func TestEncryptDecrypt(t *testing.T) { // there are many tests on the underlying codebase for that. If it's not // encrypting, compare it to the cleartext to verify because we can. if c.f == "decrypt" { - expected, err := ioutil.ReadFile(c.exp) + expected, err := os.ReadFile(c.exp) assert.NoError(t, err) assert.Equal(t, strings.TrimSpace(string(expected)), strings.TrimSpace(string(got))) diff --git a/internal/cmd/commands/workerscmd/worker-led_funcs.go b/internal/cmd/commands/workerscmd/worker-led_funcs.go index be947251e..134537551 100644 --- a/internal/cmd/commands/workerscmd/worker-led_funcs.go +++ b/internal/cmd/commands/workerscmd/worker-led_funcs.go @@ -42,8 +42,8 @@ func (c *WorkerLedCommand) extraWorkerLedHelpFunc(helpMap map[string]func() stri return helpStr + c.Flags().Help() } -func extraWorkerLedFlagsFuncImpl(c *WorkerLedCommand, set *base.FlagSets, f *base.FlagSet) { - f = set.NewFlagSet("Worker Creation Options") +func extraWorkerLedFlagsFuncImpl(c *WorkerLedCommand, set *base.FlagSets, _ *base.FlagSet) { + f := set.NewFlagSet("Worker Creation Options") for _, name := range flagsWorkerLedMap[c.Func] { switch name { diff --git a/internal/cmd/config/config_load_test.go b/internal/cmd/config/config_load_test.go index 16bd1526f..526fc5e28 100644 --- a/internal/cmd/config/config_load_test.go +++ b/internal/cmd/config/config_load_test.go @@ -6,8 +6,8 @@ package config_test import ( "context" "fmt" - "io/ioutil" "net/http" + "os" "testing" "time" @@ -1857,7 +1857,7 @@ func TestLoad(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { var paths []string - files, err := ioutil.ReadDir(fmt.Sprintf("testdata/%s", t.Name())) + files, err := os.ReadDir(fmt.Sprintf("testdata/%s", t.Name())) require.NoError(t, err) for _, file := range files { if !file.IsDir() { diff --git a/internal/cmd/ops/server_test.go b/internal/cmd/ops/server_test.go index e575485fe..1f46bd7b7 100644 --- a/internal/cmd/ops/server_test.go +++ b/internal/cmd/ops/server_test.go @@ -12,7 +12,6 @@ import ( "encoding/pem" "fmt" "io" - "io/ioutil" "math/big" "net" "net/http" @@ -21,7 +20,6 @@ import ( "testing" "time" - "github.com/golang/protobuf/jsonpb" "github.com/google/go-cmp/cmp" "github.com/hashicorp/boundary/internal/cmd/base" "github.com/hashicorp/boundary/internal/daemon/controller" @@ -38,6 +36,7 @@ import ( "github.com/mitchellh/cli" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/testing/protocmp" "google.golang.org/protobuf/types/known/wrapperspb" ) @@ -721,7 +720,9 @@ func TestCreateOpsHandler(t *testing.T) { require.NoError(t, err) // We can do the GET request require.Equal(t, http.StatusOK, rsp.StatusCode) // And the endpoint exists pbResp := &pbs.GetHealthResponse{} - require.NoError(t, jsonpb.Unmarshal(rsp.Body, pbResp)) + body, err = io.ReadAll(rsp.Body) + require.NoError(t, err) + require.NoError(t, protojson.Unmarshal(body, pbResp)) want := &pbs.GetHealthResponse{WorkerProcessInfo: &pbhealth.HealthInfo{ State: server.ActiveOperationalState.String(), ActiveSessionCount: wrapperspb.UInt32(0), @@ -752,7 +753,9 @@ func TestCreateOpsHandler(t *testing.T) { require.NoError(t, err) // We can do the GET request require.Equal(t, http.StatusOK, rsp.StatusCode) // And the endpoint exists pbResp := &pbs.GetHealthResponse{} - require.NoError(t, jsonpb.Unmarshal(rsp.Body, pbResp)) + body, err = io.ReadAll(rsp.Body) + require.NoError(t, err) + require.NoError(t, protojson.Unmarshal(body, pbResp)) want := &pbs.GetHealthResponse{WorkerProcessInfo: &pbhealth.HealthInfo{ State: server.ActiveOperationalState.String(), ActiveSessionCount: wrapperspb.UInt32(0), @@ -932,7 +935,7 @@ func testTlsHttpClient(t *testing.T, certPath string) *http.Client { f, err := os.Open(certPath) require.NoError(t, err) - certBytes, err := ioutil.ReadAll(f) + certBytes, err := io.ReadAll(f) require.NoError(t, err) require.NoError(t, f.Close()) diff --git a/internal/credential/static/repository_credential_store_test.go b/internal/credential/static/repository_credential_store_test.go index fdafc5af2..f367e31ae 100644 --- a/internal/credential/static/repository_credential_store_test.go +++ b/internal/credential/static/repository_credential_store_test.go @@ -152,6 +152,7 @@ func TestRepository_CreateCredentialStore(t *testing.T) { // Creating credential in different project should not conflict in3, err := NewCredentialStore(prj2.GetPublicId(), WithName("my-name"), WithDescription("desc")) + require.NoError(err) got3, err := repo.CreateCredentialStore(ctx, in3) require.NoError(err) assert.Equal(in.Name, got3.Name) diff --git a/internal/credential/static/repository_credential_test.go b/internal/credential/static/repository_credential_test.go index a530a1d59..cd64e9202 100644 --- a/internal/credential/static/repository_credential_test.go +++ b/internal/credential/static/repository_credential_test.go @@ -190,6 +190,7 @@ func TestRepository_CreateUsernamePasswordCredential(t *testing.T) { // Creating credential in different project should not conflict in3, err := NewUsernamePasswordCredential(prj2Cs.GetPublicId(), "user", "pass", WithName("my-name"), WithDescription("different")) + require.NoError(err) got3, err := repo.CreateUsernamePasswordCredential(ctx, prj2.GetPublicId(), in3) require.NoError(err) assert.Equal(in3.Name, got3.Name) diff --git a/internal/credential/vault/jobs.go b/internal/credential/vault/jobs.go index a0372818b..353beb82f 100644 --- a/internal/credential/vault/jobs.go +++ b/internal/credential/vault/jobs.go @@ -132,7 +132,7 @@ func (r *TokenRenewalJob) Status() scheduler.JobStatus { // already running an error with code JobAlreadyRunning will be returned. func (r *TokenRenewalJob) Run(ctx context.Context) error { const op = "vault.(TokenRenewalJob).Run" - if !r.running.CAS(r.running.Load(), true) { + if !r.running.CompareAndSwap(r.running.Load(), true) { return errors.New(ctx, errors.JobAlreadyRunning, op, "job already running") } defer r.running.Store(false) @@ -270,7 +270,7 @@ func nextRenewal(ctx context.Context, j scheduler.Job) (time.Duration, error) { } defer rows.Close() - for rows.Next() { + if rows.Next() { type NextRenewal struct { RenewalIn time.Duration } @@ -358,7 +358,7 @@ func (r *TokenRevocationJob) Status() scheduler.JobStatus { // already running an error with code JobAlreadyRunning will be returned. func (r *TokenRevocationJob) Run(ctx context.Context) error { const op = "vault.(TokenRevocationJob).Run" - if !r.running.CAS(r.running.Load(), true) { + if !r.running.CompareAndSwap(r.running.Load(), true) { return errors.New(ctx, errors.JobAlreadyRunning, op, "job already running") } defer r.running.Store(false) @@ -523,7 +523,7 @@ func (r *CredentialRenewalJob) Status() scheduler.JobStatus { // already running an error with code JobAlreadyRunning will be returned. func (r *CredentialRenewalJob) Run(ctx context.Context) error { const op = "vault.(CredentialRenewalJob).Run" - if !r.running.CAS(r.running.Load(), true) { + if !r.running.CompareAndSwap(r.running.Load(), true) { return errors.New(ctx, errors.JobAlreadyRunning, op, "job already running") } defer r.running.Store(false) @@ -686,7 +686,7 @@ func (r *CredentialRevocationJob) Status() scheduler.JobStatus { // already running an error with code JobAlreadyRunning will be returned. func (r *CredentialRevocationJob) Run(ctx context.Context) error { const op = "vault.(CredentialRevocationJob).Run" - if !r.running.CAS(r.running.Load(), true) { + if !r.running.CompareAndSwap(r.running.Load(), true) { return errors.New(ctx, errors.JobAlreadyRunning, op, "job already running") } defer r.running.Store(false) @@ -827,7 +827,7 @@ func (r *CredentialStoreCleanupJob) Status() scheduler.JobStatus { // JobAlreadyRunning will be returned. func (r *CredentialStoreCleanupJob) Run(ctx context.Context) error { const op = "vault.(CredentialStoreCleanupJob).Run" - if !r.running.CAS(r.running.Load(), true) { + if !r.running.CompareAndSwap(r.running.Load(), true) { return errors.New(ctx, errors.JobAlreadyRunning, op, "job already running") } defer r.running.Store(false) @@ -927,7 +927,7 @@ func (r *CredentialCleanupJob) Status() scheduler.JobStatus { // JobAlreadyRunning will be returned. func (r *CredentialCleanupJob) Run(ctx context.Context) error { const op = "vault.(CredentialCleanupJob).Run" - if !r.running.CAS(r.running.Load(), true) { + if !r.running.CompareAndSwap(r.running.Load(), true) { return errors.New(ctx, errors.JobAlreadyRunning, op, "job already running") } defer r.running.Store(false) diff --git a/internal/credential/vault/supported.go b/internal/credential/vault/supported.go index 999413d38..b65ad6317 100644 --- a/internal/credential/vault/supported.go +++ b/internal/credential/vault/supported.go @@ -9,7 +9,6 @@ package vault import ( "crypto/tls" "fmt" - "io/ioutil" "net/http" "os" "path" @@ -128,11 +127,11 @@ func gotNewServer(t testing.TB, opt ...TestOption) *TestVaultServer { dataSrcDir := t.TempDir() require.NoError(os.Chmod(dataSrcDir, 0o777)) caCertFn := filepath.Join(dataSrcDir, "ca-certificate.pem") - require.NoError(ioutil.WriteFile(caCertFn, serverCert.CA.Cert, 0o777)) + require.NoError(os.WriteFile(caCertFn, serverCert.CA.Cert, 0o777)) certFn := filepath.Join(dataSrcDir, "certificate.pem") - require.NoError(ioutil.WriteFile(certFn, serverCert.Cert.Cert, 0o777)) + require.NoError(os.WriteFile(certFn, serverCert.Cert.Cert, 0o777)) keyFn := filepath.Join(dataSrcDir, "key.pem") - require.NoError(ioutil.WriteFile(keyFn, serverCert.Cert.Key, 0o777)) + require.NoError(os.WriteFile(keyFn, serverCert.Cert.Key, 0o777)) dockerOptions.Mounts = append(dockerOptions.Mounts, fmt.Sprintf("%s:/vault/config/certificates", dataSrcDir)) if opts.vaultTLS == TestClientTLS { @@ -141,7 +140,7 @@ func gotNewServer(t testing.TB, opt ...TestOption) *TestVaultServer { server.ClientCert = clientCert.Cert.Cert server.ClientKey = clientCert.Cert.Key clientCaCertFn := filepath.Join(dataSrcDir, "client-ca-certificate.pem") - require.NoError(ioutil.WriteFile(clientCaCertFn, clientCert.CA.Cert, 0o777)) + require.NoError(os.WriteFile(clientCaCertFn, clientCert.CA.Cert, 0o777)) vaultClientCert, err := tls.X509KeyPair(server.ClientCert, server.ClientKey) require.NoError(err) diff --git a/internal/credential/vault/vault.go b/internal/credential/vault/vault.go index 21305cfa9..5c8d249a7 100644 --- a/internal/credential/vault/vault.go +++ b/internal/credential/vault/vault.go @@ -244,25 +244,12 @@ func (c *client) capabilities(ctx context.Context, paths []string) (pathCapabili if len(paths) == 0 { return nil, errors.New(ctx, errors.InvalidParameter, op, "empty paths") } - body := map[string]string{ + body := map[string]any{ "paths": strings.Join(paths, ","), } - reqPath := "/v1/sys/capabilities-self" + reqPath := "sys/capabilities-self" - r := c.cl.NewRequest("POST", reqPath) - if err := r.SetJSONBody(body); err != nil { - return nil, err - } - - ctx, cancelFunc := context.WithCancel(context.Background()) - defer cancelFunc() - resp, err := c.cl.RawRequestWithContext(ctx, r) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - secret, err := vault.ParseSecret(resp.Body) + secret, err := c.cl.Logical().WriteWithContext(ctx, reqPath, body) if err != nil { return nil, err } diff --git a/internal/credential/vault/vault_capabilities.go b/internal/credential/vault/vault_capabilities.go index 2db07044f..0ee6321b0 100644 --- a/internal/credential/vault/vault_capabilities.go +++ b/internal/credential/vault/vault_capabilities.go @@ -172,8 +172,8 @@ func (pc pathCapabilities) get(path string) (capabilities, bool) { // union creates and returns a new pathCapabilities instance, z. union sets // z[p] = x[p] | y[p] for all p, where p is a path from the set of paths // from x and y. -func (x pathCapabilities) union(y pathCapabilities) (z pathCapabilities) { - if len(x) == 0 && len(y) == 0 { +func (pc pathCapabilities) union(y pathCapabilities) (z pathCapabilities) { + if len(pc) == 0 && len(y) == 0 { return } max := func(a, b int) int { @@ -182,12 +182,12 @@ func (x pathCapabilities) union(y pathCapabilities) (z pathCapabilities) { } return b } - z = make(pathCapabilities, max(len(x), len(y))) - for p := range x { - z[p] = x[p] | y[p] + z = make(pathCapabilities, max(len(pc), len(y))) + for p := range pc { + z[p] = pc[p] | y[p] } for p := range y { - z[p] = x[p] | y[p] + z[p] = pc[p] | y[p] } return } diff --git a/internal/daemon/cluster/handlers/worker_service_status_test.go b/internal/daemon/cluster/handlers/worker_service_status_test.go index bd4f8d5aa..20a73f75c 100644 --- a/internal/daemon/cluster/handlers/worker_service_status_test.go +++ b/internal/daemon/cluster/handlers/worker_service_status_test.go @@ -789,6 +789,7 @@ func TestStatusDeadConnection(t *testing.T) { } got, err := s.Status(ctx, req) + require.NoError(t, err) assert.Empty(t, cmp.Diff( want, @@ -1205,8 +1206,10 @@ func TestStatusAuthorizedWorkers(t *testing.T) { assert.Equal(tc.wantErrMsg, err.Error()) return } - sort.Strings(got.GetAuthorizedWorkers().GetWorkerKeyIdentifiers()) - sort.Strings(tc.want.GetAuthorizedWorkers().GetWorkerKeyIdentifiers()) + gotAuthorizedWorkers := got.GetAuthorizedWorkers() + sort.Strings(gotAuthorizedWorkers.GetWorkerKeyIdentifiers()) + wantAuthorizedWorkers := tc.want.GetAuthorizedWorkers() + sort.Strings(wantAuthorizedWorkers.GetWorkerKeyIdentifiers()) sort.Strings(got.GetAuthorizedDownstreamWorkers().GetWorkerPublicIds()) sort.Strings(tc.want.GetAuthorizedDownstreamWorkers().GetWorkerPublicIds()) sort.Strings(got.GetAuthorizedDownstreamWorkers().GetUnmappedWorkerKeyIdentifiers()) diff --git a/internal/daemon/common/handler_test.go b/internal/daemon/common/handler_test.go index 0c617e088..9c8e69aa2 100644 --- a/internal/daemon/common/handler_test.go +++ b/internal/daemon/common/handler_test.go @@ -8,7 +8,6 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" "net" "net/http" "net/http/httptest" @@ -286,7 +285,7 @@ func Test_WrapWithEventsHandler(t *testing.T) { { // test that the got observation is what we wanted. require.NotNil(c.ObservationEvents) defer func() { _ = os.WriteFile(c.ObservationEvents.Name(), nil, 0o666) }() - b, err := ioutil.ReadFile(c.ObservationEvents.Name()) + b, err := os.ReadFile(c.ObservationEvents.Name()) assert.NoError(err) if tt.noEventJson { @@ -320,7 +319,7 @@ func Test_WrapWithEventsHandler(t *testing.T) { { // test that the got audit is what we wanted. require.NotNil(c.AuditEvents) defer func() { _ = os.WriteFile(c.AuditEvents.Name(), nil, 0o666) }() - b, err := ioutil.ReadFile(c.AuditEvents.Name()) + b, err := os.ReadFile(c.AuditEvents.Name()) assert.NoError(err) got := &cloudevents.Event{} diff --git a/internal/daemon/controller/gateway.go b/internal/daemon/controller/gateway.go index a832184b0..22317e002 100644 --- a/internal/daemon/controller/gateway.go +++ b/internal/daemon/controller/gateway.go @@ -20,6 +20,7 @@ import ( "github.com/hashicorp/boundary/internal/kms" "github.com/hashicorp/boundary/internal/types/subtypes" "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/test/bufconn" ) @@ -32,7 +33,7 @@ type grpcServerListener interface { func gatewayDialOptions(lis grpcServerListener) []grpc.DialOption { return []grpc.DialOption{ - grpc.WithInsecure(), + grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) { return lis.Dial() }), diff --git a/internal/daemon/controller/handler.go b/internal/daemon/controller/handler.go index 9d6f90d8e..299198a02 100644 --- a/internal/daemon/controller/handler.go +++ b/internal/daemon/controller/handler.go @@ -9,7 +9,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/textproto" "os" @@ -702,7 +702,7 @@ func wrapHandlerWithCallbackInterceptor(h http.Handler, c *Controller) http.Hand } } bytesReader := bytes.NewReader(attrBytes) - req.Body = ioutil.NopCloser(bytesReader) + req.Body = io.NopCloser(bytesReader) req.ContentLength = int64(bytesReader.Len()) req.Header.Set(textproto.CanonicalMIMEHeaderKey("content-type"), "application/json") req.Method = http.MethodPost diff --git a/internal/daemon/controller/handler_test.go b/internal/daemon/controller/handler_test.go index 5f2fadfdd..f1a5262ae 100644 --- a/internal/daemon/controller/handler_test.go +++ b/internal/daemon/controller/handler_test.go @@ -10,7 +10,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net" "net/http" "net/url" @@ -50,7 +49,7 @@ func TestAuthenticationHandler(t *testing.T) { require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode, "Got response: %v", resp) - b, err = ioutil.ReadAll(resp.Body) + b, err = io.ReadAll(resp.Body) require.NoError(t, err) body := make(map[string]any) require.NoError(t, json.Unmarshal(b, &body)) @@ -71,7 +70,7 @@ func TestAuthenticationHandler(t *testing.T) { require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode, "Got response: %v", resp) - b, err = ioutil.ReadAll(resp.Body) + b, err = io.ReadAll(resp.Body) require.NoError(t, err) body = make(map[string]any) require.NoError(t, json.Unmarshal(b, &body)) diff --git a/internal/daemon/controller/handlers/authmethods/ldap_test.go b/internal/daemon/controller/handlers/authmethods/ldap_test.go index f35ea941d..2f6c95f38 100644 --- a/internal/daemon/controller/handlers/authmethods/ldap_test.go +++ b/internal/daemon/controller/handlers/authmethods/ldap_test.go @@ -7,7 +7,6 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" "os" "strings" "sync" @@ -1126,7 +1125,7 @@ func TestAuthenticate_Ldap(t *testing.T) { assert.Equal(tc.wantType, resp.GetType()) sinkFileName := c.ObservationEvents.Name() defer func() { _ = os.WriteFile(sinkFileName, nil, 0o666) }() - b, err := ioutil.ReadFile(sinkFileName) + b, err := os.ReadFile(sinkFileName) require.NoError(err) gotRes := &cloudevents.Event{} err = json.Unmarshal(b, gotRes) diff --git a/internal/daemon/controller/handlers/errors_test.go b/internal/daemon/controller/handlers/errors_test.go index 4614e9ba2..73ee5b355 100644 --- a/internal/daemon/controller/handlers/errors_test.go +++ b/internal/daemon/controller/handlers/errors_test.go @@ -7,7 +7,7 @@ import ( "context" stderrors "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -251,7 +251,7 @@ func TestApiErrorHandler(t *testing.T) { resp := w.Result() assert.EqualValues(tc.expected.Status, resp.StatusCode) - got, err := ioutil.ReadAll(resp.Body) + got, err := io.ReadAll(resp.Body) require.NoError(err) gotErr := &pb.Error{} diff --git a/internal/daemon/controller/handlers/scopes/scope_service_test.go b/internal/daemon/controller/handlers/scopes/scope_service_test.go index f9cef4734..19797a16d 100644 --- a/internal/daemon/controller/handlers/scopes/scope_service_test.go +++ b/internal/daemon/controller/handlers/scopes/scope_service_test.go @@ -1428,7 +1428,7 @@ func TestUpdate(t *testing.T) { var orgVersion uint32 = 2 var projVersion uint32 = 2 - var globalVersion uint32 = global.Version + globalVersion := global.Version resetOrg := func() { orgVersion++ diff --git a/internal/daemon/controller/handlers/targets/target_service.go b/internal/daemon/controller/handlers/targets/target_service.go index 0be8a5384..e089d329c 100644 --- a/internal/daemon/controller/handlers/targets/target_service.go +++ b/internal/daemon/controller/handlers/targets/target_service.go @@ -1716,16 +1716,17 @@ func validateGetRequest(req *pbs.GetTargetRequest) error { } func validateCreateRequest(req *pbs.CreateTargetRequest) error { - return handlers.ValidateCreateRequest(req.GetItem(), func() map[string]string { + item := req.GetItem() + return handlers.ValidateCreateRequest(item, func() map[string]string { badFields := map[string]string{} - if !handlers.ValidId(handlers.Id(req.GetItem().GetScopeId()), scope.Project.Prefix()) { + if !handlers.ValidId(handlers.Id(item.GetScopeId()), scope.Project.Prefix()) { badFields[globals.ScopeIdField] = "This field is required to have a properly formatted project scope id." } - if req.GetItem().GetName() == nil || req.GetItem().GetName().GetValue() == "" { + if item.GetName() == nil || item.GetName().GetValue() == "" { badFields[globals.NameField] = "This field is required." } - if req.GetItem().GetSessionConnectionLimit() != nil { - val := req.GetItem().GetSessionConnectionLimit().GetValue() + if item.GetSessionConnectionLimit() != nil { + val := item.GetSessionConnectionLimit().GetValue() switch { case val == -1: case val > 0: @@ -1733,29 +1734,29 @@ func validateCreateRequest(req *pbs.CreateTargetRequest) error { badFields[globals.SessionConnectionLimitField] = "This must be -1 (unlimited) or greater than zero." } } - if req.GetItem().GetSessionMaxSeconds() != nil && req.GetItem().GetSessionMaxSeconds().GetValue() == 0 { + if item.GetSessionMaxSeconds() != nil && item.GetSessionMaxSeconds().GetValue() == 0 { badFields[globals.SessionMaxSecondsField] = "This must be greater than zero." } - if req.GetItem().GetType() == "" { + if item.GetType() == "" { badFields[globals.TypeField] = "This is a required field." - } else if target.SubtypeFromType(req.GetItem().GetType()) == "" { + } else if target.SubtypeFromType(item.GetType()) == "" { badFields[globals.TypeField] = "Unknown type provided." } - if workerFilter := req.GetItem().GetWorkerFilter(); workerFilter != nil { + if workerFilter := item.GetWorkerFilter(); workerFilter != nil { badFields[globals.WorkerFilterField] = WorkerFilterDeprecationMessage } - if egressFilter := req.GetItem().GetEgressWorkerFilter(); egressFilter != nil { + if egressFilter := item.GetEgressWorkerFilter(); egressFilter != nil { if _, err := bexpr.CreateEvaluator(egressFilter.GetValue()); err != nil { badFields[globals.EgressWorkerFilterField] = "Unable to successfully parse egress filter expression." } } - if ingressFilter := req.GetItem().GetIngressWorkerFilter(); ingressFilter != nil { + if ingressFilter := item.GetIngressWorkerFilter(); ingressFilter != nil { err := ValidateIngressWorkerFilterFn(ingressFilter.GetValue()) if err != nil { badFields[globals.IngressWorkerFilterField] = err.Error() } } - if address := req.GetItem().GetAddress(); address != nil { + if address := item.GetAddress(); address != nil { if len(address.GetValue()) < static.MinHostAddressLength || len(address.GetValue()) > static.MaxHostAddressLength { badFields[globals.AddressField] = fmt.Sprintf("Address length must be between %d and %d characters.", static.MinHostAddressLength, static.MaxHostAddressLength) @@ -1769,12 +1770,12 @@ func validateCreateRequest(req *pbs.CreateTargetRequest) error { badFields[globals.AddressField] = fmt.Sprintf("Error parsing address: %v.", err) } } - subtype := target.SubtypeFromType(req.GetItem().GetType()) + subtype := target.SubtypeFromType(item.GetType()) _, err := subtypeRegistry.get(subtype) if err != nil { badFields[globals.TypeField] = "Unknown type provided." } else { - a, err := subtypeRegistry.newAttribute(subtype, req.GetItem().GetAttrs()) + a, err := subtypeRegistry.newAttribute(subtype, item.GetAttrs()) if err != nil { badFields[globals.AttributesField] = "Attribute fields do not match the expected format." } else { @@ -1788,14 +1789,15 @@ func validateCreateRequest(req *pbs.CreateTargetRequest) error { } func validateUpdateRequest(req *pbs.UpdateTargetRequest) error { + item := req.GetItem() return handlers.ValidateUpdateRequest(req, req.GetItem(), func() map[string]string { badFields := map[string]string{} paths := req.GetUpdateMask().GetPaths() - if handlers.MaskContains(paths, globals.NameField) && req.GetItem().GetName().GetValue() == "" { + if handlers.MaskContains(paths, globals.NameField) && item.GetName().GetValue() == "" { badFields[globals.NameField] = "This field cannot be set to empty." } - if req.GetItem().GetSessionConnectionLimit() != nil { - val := req.GetItem().GetSessionConnectionLimit().GetValue() + if item.GetSessionConnectionLimit() != nil { + val := item.GetSessionConnectionLimit().GetValue() switch { case val == -1: case val > 0: @@ -1803,18 +1805,18 @@ func validateUpdateRequest(req *pbs.UpdateTargetRequest) error { badFields[globals.SessionConnectionLimitField] = "This must be -1 (unlimited) or greater than zero." } } - if req.GetItem().GetSessionMaxSeconds() != nil && req.GetItem().GetSessionMaxSeconds().GetValue() == 0 { + if item.GetSessionMaxSeconds() != nil && item.GetSessionMaxSeconds().GetValue() == 0 { badFields[globals.SessionMaxSecondsField] = "This must be greater than zero." } // worker_filter is mutually exclusive from ingress and egress filter workerFilterFound := false - if workerFilter := req.GetItem().GetWorkerFilter(); workerFilter != nil { + if workerFilter := item.GetWorkerFilter(); workerFilter != nil { if _, err := bexpr.CreateEvaluator(workerFilter.GetValue()); err != nil { badFields[globals.WorkerFilterField] = "Unable to successfully parse filter expression." } workerFilterFound = true } - if egressFilter := req.GetItem().GetEgressWorkerFilter(); egressFilter != nil { + if egressFilter := item.GetEgressWorkerFilter(); egressFilter != nil { if workerFilterFound { badFields[globals.EgressWorkerFilterField] = fmt.Sprintf("Cannot set %s and %s; they are mutually exclusive fields.", globals.WorkerFilterField, globals.EgressWorkerFilterField) } @@ -1822,7 +1824,7 @@ func validateUpdateRequest(req *pbs.UpdateTargetRequest) error { badFields[globals.EgressWorkerFilterField] = "Unable to successfully parse egress filter expression." } } - if ingressFilter := req.GetItem().GetIngressWorkerFilter(); ingressFilter != nil { + if ingressFilter := item.GetIngressWorkerFilter(); ingressFilter != nil { if workerFilterFound { badFields[globals.IngressWorkerFilterField] = fmt.Sprintf("Cannot set %s and %s; they are mutually exclusive fields.", globals.WorkerFilterField, globals.IngressWorkerFilterField) } @@ -1831,7 +1833,7 @@ func validateUpdateRequest(req *pbs.UpdateTargetRequest) error { badFields[globals.IngressWorkerFilterField] = err.Error() } } - if address := req.GetItem().GetAddress(); address != nil { + if address := item.GetAddress(); address != nil { if len(address.GetValue()) < static.MinHostAddressLength || len(address.GetValue()) > static.MaxHostAddressLength { badFields[globals.AddressField] = fmt.Sprintf("Address length must be between %d and %d characters.", static.MinHostAddressLength, static.MaxHostAddressLength) @@ -1850,11 +1852,11 @@ func validateUpdateRequest(req *pbs.UpdateTargetRequest) error { if err != nil { badFields[globals.TypeField] = "Unknown type provided." } else { - if req.GetItem().GetType() != "" && target.SubtypeFromType(req.GetItem().GetType()) != subtype { + if item.GetType() != "" && target.SubtypeFromType(item.GetType()) != subtype { badFields[globals.TypeField] = "Cannot modify the resource type." } - a, err := subtypeRegistry.newAttribute(subtype, req.GetItem().GetAttrs()) + a, err := subtypeRegistry.newAttribute(subtype, item.GetAttrs()) if err != nil { badFields[globals.AttributesField] = "Attribute fields do not match the expected format." } else { diff --git a/internal/daemon/controller/handlers/workers/worker_service_test.go b/internal/daemon/controller/handlers/workers/worker_service_test.go index f50af2633..a6bffeb9e 100644 --- a/internal/daemon/controller/handlers/workers/worker_service_test.go +++ b/internal/daemon/controller/handlers/workers/worker_service_test.go @@ -26,7 +26,6 @@ import ( "github.com/hashicorp/boundary/internal/types/action" "github.com/hashicorp/boundary/internal/types/scope" "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/scopes" - "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/workers" pb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/workers" "github.com/hashicorp/go-secure-stdlib/strutil" "github.com/hashicorp/nodeenrollment" @@ -1269,7 +1268,7 @@ func TestCreateWorkerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: "invalid-scope", WorkerGeneratedAuthToken: &wrapperspb.StringValue{Value: fetchReqFn()}, }, @@ -1283,7 +1282,7 @@ func TestCreateWorkerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), }, }, @@ -1296,7 +1295,7 @@ func TestCreateWorkerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), WorkerGeneratedAuthToken: &wrapperspb.StringValue{Value: fetchReqFn()}, Id: "invalid-id", @@ -1311,7 +1310,7 @@ func TestCreateWorkerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), WorkerGeneratedAuthToken: &wrapperspb.StringValue{Value: fetchReqFn()}, Address: "invalid-address", @@ -1326,7 +1325,7 @@ func TestCreateWorkerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), WorkerGeneratedAuthToken: &wrapperspb.StringValue{Value: fetchReqFn()}, ConfigTags: map[string]*structpb.ListValue{ @@ -1345,7 +1344,7 @@ func TestCreateWorkerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), WorkerGeneratedAuthToken: &wrapperspb.StringValue{Value: fetchReqFn()}, CanonicalTags: map[string]*structpb.ListValue{ @@ -1364,7 +1363,7 @@ func TestCreateWorkerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), WorkerGeneratedAuthToken: &wrapperspb.StringValue{Value: fetchReqFn()}, LastStatusTime: timestamppb.Now(), @@ -1379,7 +1378,7 @@ func TestCreateWorkerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), WorkerGeneratedAuthToken: &wrapperspb.StringValue{Value: fetchReqFn()}, AuthorizedActions: []string{"invalid-authorized-actions"}, @@ -1394,7 +1393,7 @@ func TestCreateWorkerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), WorkerGeneratedAuthToken: &wrapperspb.StringValue{Value: fetchReqFn()}, CreatedTime: timestamppb.Now(), @@ -1409,7 +1408,7 @@ func TestCreateWorkerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), WorkerGeneratedAuthToken: &wrapperspb.StringValue{Value: fetchReqFn()}, UpdatedTime: timestamppb.Now(), @@ -1424,7 +1423,7 @@ func TestCreateWorkerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), WorkerGeneratedAuthToken: &wrapperspb.StringValue{Value: fetchReqFn()}, Version: 1, @@ -1439,7 +1438,7 @@ func TestCreateWorkerLed(t *testing.T) { service: testSrv, scopeId: "splat-auth-scope", req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), WorkerGeneratedAuthToken: &wrapperspb.StringValue{Value: fetchReqFn()}, }, @@ -1452,7 +1451,7 @@ func TestCreateWorkerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), WorkerGeneratedAuthToken: &wrapperspb.StringValue{Value: "invalid;semicolon"}, }, @@ -1465,7 +1464,7 @@ func TestCreateWorkerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), WorkerGeneratedAuthToken: &wrapperspb.StringValue{Value: "notNodeCreds"}, }, @@ -1485,7 +1484,7 @@ func TestCreateWorkerLed(t *testing.T) { }(), scopeId: scope.Global.String(), req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), Name: &wrapperspb.StringValue{Value: "success"}, Description: &wrapperspb.StringValue{Value: "success-description"}, @@ -1518,7 +1517,7 @@ func TestCreateWorkerLed(t *testing.T) { }(), scopeId: scope.Global.String(), req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), Name: &wrapperspb.StringValue{Value: "success"}, Description: &wrapperspb.StringValue{Value: "success-description"}, @@ -1533,7 +1532,7 @@ func TestCreateWorkerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateWorkerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), Name: &wrapperspb.StringValue{Value: "success"}, Description: &wrapperspb.StringValue{Value: "success-description"}, @@ -1541,7 +1540,7 @@ func TestCreateWorkerLed(t *testing.T) { }, }, res: &pbs.CreateWorkerLedResponse{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), Name: &wrapperspb.StringValue{Value: "success"}, Description: &wrapperspb.StringValue{Value: "success-description"}, @@ -1652,7 +1651,7 @@ func TestCreateControllerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateControllerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: "invalid-scope", }, }, @@ -1665,7 +1664,7 @@ func TestCreateControllerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateControllerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), WorkerGeneratedAuthToken: &wrapperspb.StringValue{Value: fetchReqFn()}, }, @@ -1679,7 +1678,7 @@ func TestCreateControllerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateControllerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), Id: "invalid-id", }, @@ -1693,7 +1692,7 @@ func TestCreateControllerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateControllerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), Address: "invalid-address", }, @@ -1707,7 +1706,7 @@ func TestCreateControllerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateControllerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), ConfigTags: map[string]*structpb.ListValue{ "invalid": {Values: []*structpb.Value{ @@ -1725,7 +1724,7 @@ func TestCreateControllerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateControllerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), CanonicalTags: map[string]*structpb.ListValue{ "invalid": {Values: []*structpb.Value{ @@ -1743,7 +1742,7 @@ func TestCreateControllerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateControllerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), LastStatusTime: timestamppb.Now(), }, @@ -1757,7 +1756,7 @@ func TestCreateControllerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateControllerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), AuthorizedActions: []string{"invalid-authorized-actions"}, }, @@ -1771,7 +1770,7 @@ func TestCreateControllerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateControllerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), CreatedTime: timestamppb.Now(), }, @@ -1785,7 +1784,7 @@ func TestCreateControllerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateControllerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), UpdatedTime: timestamppb.Now(), }, @@ -1799,7 +1798,7 @@ func TestCreateControllerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateControllerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), Version: 1, }, @@ -1813,7 +1812,7 @@ func TestCreateControllerLed(t *testing.T) { service: testSrv, scopeId: "splat-auth-scope", req: &pbs.CreateControllerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), }, }, @@ -1832,7 +1831,7 @@ func TestCreateControllerLed(t *testing.T) { }(), scopeId: scope.Global.String(), req: &pbs.CreateControllerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), Name: &wrapperspb.StringValue{Value: "success"}, Description: &wrapperspb.StringValue{Value: "success-description"}, @@ -1864,7 +1863,7 @@ func TestCreateControllerLed(t *testing.T) { }(), scopeId: scope.Global.String(), req: &pbs.CreateControllerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), Name: &wrapperspb.StringValue{Value: "success"}, Description: &wrapperspb.StringValue{Value: "success-description"}, @@ -1878,14 +1877,14 @@ func TestCreateControllerLed(t *testing.T) { service: testSrv, scopeId: scope.Global.String(), req: &pbs.CreateControllerLedRequest{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), Name: &wrapperspb.StringValue{Value: "success"}, Description: &wrapperspb.StringValue{Value: "success-description"}, }, }, res: &pbs.CreateControllerLedResponse{ - Item: &workers.Worker{ + Item: &pb.Worker{ ScopeId: scope.Global.String(), Name: &wrapperspb.StringValue{Value: "success"}, Description: &wrapperspb.StringValue{Value: "success-description"}, diff --git a/internal/daemon/controller/listeners_test.go b/internal/daemon/controller/listeners_test.go index a1b446e29..306a19048 100644 --- a/internal/daemon/controller/listeners_test.go +++ b/internal/daemon/controller/listeners_test.go @@ -355,10 +355,12 @@ func TestStopClusterGrpcServerAndListener(t *testing.T) { go grpcServer.Serve(l) // Make sure it's up - _, err = grpc.Dial(l.Addr().String(), - grpc.WithInsecure(), + grpcCtx, grpcCtxCancel := context.WithTimeout(context.Background(), 5*time.Second) + t.Cleanup(grpcCtxCancel) + _, err = grpc.DialContext(grpcCtx, + l.Addr().String(), + grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), - grpc.WithTimeout(5*time.Second), ) require.NoError(t, err) @@ -557,11 +559,13 @@ func TestStopApiGrpcServerAndListener(t *testing.T) { go grpcServer.Serve(l) // Make sure it's up - _, err := grpc.Dial("", - grpc.WithInsecure(), + grpcCtx, grpcCtxCancel := context.WithTimeout(context.Background(), 10*time.Second) + t.Cleanup(grpcCtxCancel) + _, err := grpc.DialContext(grpcCtx, + "", + grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithBlock(), - grpc.WithTimeout(10*time.Second), - grpc.WithDialer(func(s string, d time.Duration) (net.Conn, error) { + grpc.WithContextDialer(func(ctx context.Context, s string) (net.Conn, error) { return l.Dial() }), ) diff --git a/internal/daemon/controller/testing.go b/internal/daemon/controller/testing.go index 0e333e4f6..8c043e71b 100644 --- a/internal/daemon/controller/testing.go +++ b/internal/daemon/controller/testing.go @@ -44,6 +44,7 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/require" "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/test/bufconn" ) @@ -978,7 +979,7 @@ func startTestGreeterService(t testing.TB, greeter interceptor.GreeterServiceSer conn, _ := grpc.DialContext(dialCtx, "", grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) { return listener.Dial() - }), grpc.WithInsecure()) + }), grpc.WithTransportCredentials(insecure.NewCredentials())) t.Cleanup(func() { listener.Close() diff --git a/internal/daemon/controller/tickers.go b/internal/daemon/controller/tickers.go index f3694d9f3..ff7dcb552 100644 --- a/internal/daemon/controller/tickers.go +++ b/internal/daemon/controller/tickers.go @@ -25,7 +25,8 @@ const ( terminationInterval = 1 * time.Minute ) -// This is exported so it can be tweaked in tests +// NonceCleanupInterval is the interval to wait between nonce cleanups. This is +// exported so it can be tweaked in tests var NonceCleanupInterval = 2 * time.Minute func (c *Controller) startStatusTicking(cancelCtx context.Context) { @@ -116,10 +117,9 @@ func (c *Controller) startTerminateCompletedSessionsTicking(cancelCtx context.Co if err != nil { event.WriteError(cancelCtx, op, err, event.WithInfoMsg("error fetching repository for terminating completed sessions")) } else { - terminationCount, err := repo.TerminateCompletedSessions(cancelCtx) + _, err := repo.TerminateCompletedSessions(cancelCtx) if err != nil { event.WriteError(cancelCtx, op, err, event.WithInfoMsg("error performing termination of completed sessions")) - } else if terminationCount > 0 { } } timer.Reset(getRandomInterval()) diff --git a/internal/daemon/worker/session/manager.go b/internal/daemon/worker/session/manager.go index 0bf67e35f..81b415d6f 100644 --- a/internal/daemon/worker/session/manager.go +++ b/internal/daemon/worker/session/manager.go @@ -14,6 +14,8 @@ import ( pbs "github.com/hashicorp/boundary/internal/gen/controller/servers/services" ) +// CloseCallTimeout is a timeout value +// // FIXME: This is really ugly -- but not as ugly as plumbing this value into the // interface. We should figure out something better. For now, it will at least // keep sync with any changes to the value once it's initialized as the worker diff --git a/internal/daemon/worker/status.go b/internal/daemon/worker/status.go index 150ac0804..ae9c86143 100644 --- a/internal/daemon/worker/status.go +++ b/internal/daemon/worker/status.go @@ -357,7 +357,7 @@ func (w *Worker) sendWorkerStatus(cancelCtx context.Context, sessionManager sess w.cleanupConnections(cancelCtx, false, sessionManager) // If we have post hooks for after the first status check, run them now - if w.everAuthenticated.CAS(authenticationStatusFirstAuthentication, authenticationStatusFirstStatusRpcSuccessful) { + if w.everAuthenticated.CompareAndSwap(authenticationStatusFirstAuthentication, authenticationStatusFirstStatusRpcSuccessful) { if downstreamWorkersFactory != nil { w.downstreamWorkers, err = downstreamWorkersFactory(cancelCtx, w.LastStatusSuccess().WorkerId, versionInfo.FullVersionNumber(false)) if err != nil { diff --git a/internal/db/backoff.go b/internal/db/backoff.go index 7eaeddeda..485b8f48d 100644 --- a/internal/db/backoff.go +++ b/internal/db/backoff.go @@ -14,11 +14,11 @@ type Backoff interface { } type ConstBackoff struct { - DurationMs time.Duration + Amount time.Duration } func (b ConstBackoff) Duration(attempt uint) time.Duration { - return time.Millisecond * time.Duration(b.DurationMs) + return time.Millisecond * time.Duration(b.Amount) } type ExpBackoff struct{} diff --git a/internal/db/db.go b/internal/db/db.go index e2961829f..1f3a9a58c 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -68,18 +68,18 @@ var CloseSwappedDbDuration = 5 * time.Minute // Swap replaces *DB's underlying database object with the one from `newDB`. // It returns a function that calls Close() on the outgoing database object. // Note: Swap does not verify the incoming *DB object is correctly set-up. -func (db *DB) Swap(ctx context.Context, newDB *DB) (closeDbFn, error) { +func (d *DB) Swap(ctx context.Context, newDB *DB) (closeDbFn, error) { const op = "db.(DB).Swap" if newDB == nil || newDB.wrapped == nil || newDB.wrapped.Load() == nil { return nil, fmt.Errorf("no new db object present") } - if db == nil || db.wrapped == nil || db.wrapped.Load() == nil { + if d == nil || d.wrapped == nil || d.wrapped.Load() == nil { // TBD: We could be helpful here and set the new DB instead of err? return nil, fmt.Errorf("no current db is present to swap, aborting") } // Grab the old db to allow for cleanup after swap. - oldDbw := db.wrapped.Swap(newDB.wrapped.Load()) + oldDbw := d.wrapped.Swap(newDB.wrapped.Load()) closeOldDbFn := func(ctx context.Context) { go func() { maxTime := time.Now().Add(CloseSwappedDbDuration) @@ -118,8 +118,8 @@ func (db *DB) Swap(ctx context.Context, newDB *DB) (closeDbFn, error) { } // Debug will enable/disable debug info for the connection -func (db *DB) Debug(on bool) { - db.wrapped.Load().Debug(on) +func (d *DB) Debug(on bool) { + d.wrapped.Load().Debug(on) } // SqlDB returns the underlying sql.DB diff --git a/internal/db/read_writer_test.go b/internal/db/read_writer_test.go index 19a3a7f72..787b5a8ec 100644 --- a/internal/db/read_writer_test.go +++ b/internal/db/read_writer_test.go @@ -7,7 +7,6 @@ import ( "context" stderrors "errors" "fmt" - "io/ioutil" "os" "strconv" "strings" @@ -953,7 +952,7 @@ func TestDb_LookupNotFoundEvent(t *testing.T) { defer func() { _ = os.WriteFile(c.AllEvents.Name(), nil, 0o666) }() - b, err := ioutil.ReadFile(c.AllEvents.Name()) + b, err := os.ReadFile(c.AllEvents.Name()) require.NoError(err) // No events should have been written with the above error assert.Len(b, 0) @@ -975,7 +974,7 @@ func TestDb_LookupNotFoundEvent(t *testing.T) { defer func() { _ = os.WriteFile(c.AllEvents.Name(), nil, 0o666) }() - b, err := ioutil.ReadFile(c.AllEvents.Name()) + b, err := os.ReadFile(c.AllEvents.Name()) require.NoError(err) // No events should have been written with the above error assert.Len(b, 0) diff --git a/internal/db/schema/internal/postgres/postgres.go b/internal/db/schema/internal/postgres/postgres.go index e375c4e51..b3181eab6 100644 --- a/internal/db/schema/internal/postgres/postgres.go +++ b/internal/db/schema/internal/postgres/postgres.go @@ -34,7 +34,6 @@ import ( stderrors "errors" "fmt" "io" - "io/ioutil" "github.com/hashicorp/boundary/internal/db/schema/internal/log" "github.com/hashicorp/boundary/internal/db/schema/migration" @@ -213,7 +212,7 @@ func (p *Postgres) Run(ctx context.Context, migration io.Reader, version int, ed return errors.New(ctx, errors.MigrationIntegrity, op, "no pending transaction") } - migr, err := ioutil.ReadAll(migration) + migr, err := io.ReadAll(migration) if err != nil { return errors.Wrap(ctx, err, op) } diff --git a/internal/db/timestamp/timestamp.go b/internal/db/timestamp/timestamp.go index efaf12fc2..3151d1759 100644 --- a/internal/db/timestamp/timestamp.go +++ b/internal/db/timestamp/timestamp.go @@ -24,6 +24,6 @@ func Now() *Timestamp { } // AsTime converts x to a time.Time. -func (x *Timestamp) AsTime() time.Time { - return x.GetTimestamp().AsTime() +func (ts *Timestamp) AsTime() time.Time { + return ts.GetTimestamp().AsTime() } diff --git a/internal/event/context_test.go b/internal/event/context_test.go index 2d4f5f09a..8c452859d 100644 --- a/internal/event/context_test.go +++ b/internal/event/context_test.go @@ -8,7 +8,6 @@ import ( "encoding/json" stderrors "errors" "fmt" - "io/ioutil" "os" "sync" "testing" @@ -492,7 +491,7 @@ func Test_WriteObservation(t *testing.T) { } if tt.observationSinkFileName != "" { defer func() { _ = os.WriteFile(tt.observationSinkFileName, nil, 0o666) }() - b, err := ioutil.ReadFile(tt.observationSinkFileName) + b, err := os.ReadFile(tt.observationSinkFileName) assert.NoError(err) gotObservation := &cloudevents.Event{} @@ -526,7 +525,7 @@ func Test_WriteObservation(t *testing.T) { } require.NoError(event.WriteObservation(testCtx, "not-enabled", event.WithHeader(hdr), event.WithFlush())) - b, err := ioutil.ReadFile(c.AllEvents.Name()) + b, err := os.ReadFile(c.AllEvents.Name()) assert.NoError(err) assert.Len(b, 0) }) @@ -586,7 +585,7 @@ func Test_Filtering(t *testing.T) { require.NoError(event.WriteObservation(testCtx, "not-enabled", event.WithHeader(tt.hdr...), event.WithFlush())) - b, err := ioutil.ReadFile(c.AllEvents.Name()) + b, err := os.ReadFile(c.AllEvents.Name()) assert.NoError(err) switch tt.found { case true: @@ -924,7 +923,7 @@ func Test_WriteAudit(t *testing.T) { if tt.auditSinkFileName != "" { defer func() { _ = os.WriteFile(tt.auditSinkFileName, nil, 0o666) }() - b, err := ioutil.ReadFile(tt.auditSinkFileName) + b, err := os.ReadFile(tt.auditSinkFileName) require.NoError(err) gotAudit := &cloudevents.Event{} err = json.Unmarshal(b, gotAudit) @@ -978,7 +977,7 @@ func Test_WriteAudit(t *testing.T) { require.NoError(err) require.NoError(event.WriteAudit(testCtx, "not-enabled", event.WithRequest(testReq), event.WithFlush())) - b, err := ioutil.ReadFile(c.AllEvents.Name()) + b, err := os.ReadFile(c.AllEvents.Name()) assert.NoError(err) assert.Len(b, 0) }) @@ -1117,7 +1116,7 @@ func Test_WriteError(t *testing.T) { event.WriteError(tt.ctx, event.Op(op), tt.e, tt.opt...) if tt.errSinkFileName != "" { defer func() { _ = os.WriteFile(tt.errSinkFileName, nil, 0o666) }() - b, err := ioutil.ReadFile(tt.errSinkFileName) + b, err := os.ReadFile(tt.errSinkFileName) require.NoError(err) if tt.noOutput { @@ -1236,7 +1235,7 @@ func Test_WriteSysEvent(t *testing.T) { event.WriteSysEvent(tt.ctx, event.Op(op), tt.msg, tt.data...) if tt.sinkFileName != "" { defer func() { _ = os.WriteFile(tt.sinkFileName, nil, 0o666) }() - b, err := ioutil.ReadFile(tt.sinkFileName) + b, err := os.ReadFile(tt.sinkFileName) require.NoError(err) if tt.noOutput { diff --git a/internal/event/eventer_test.go b/internal/event/eventer_test.go index f1c377c3f..e1a50fd14 100644 --- a/internal/event/eventer_test.go +++ b/internal/event/eventer_test.go @@ -8,7 +8,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "strings" "sync" @@ -1122,7 +1121,7 @@ func Test_logAdapter_Write(t *testing.T) { sinkFileName := c.AllEvents.Name() defer func() { _ = os.WriteFile(sinkFileName, nil, 0o666) }() - b, err := ioutil.ReadFile(sinkFileName) + b, err := os.ReadFile(sinkFileName) require.NoError(err) gotEvent := &cloudevents.Event{} err = json.Unmarshal(b, gotEvent) diff --git a/internal/event/hclog_formatter_node.go b/internal/event/hclog_formatter_node.go index d9c83e8f2..27affbb30 100644 --- a/internal/event/hclog_formatter_node.go +++ b/internal/event/hclog_formatter_node.go @@ -110,15 +110,15 @@ func (f *hclogFormatterFilter) Rotate(w wrapping.Wrapper, _ ...Option) error { } // Reopen is a no op -func (_ *hclogFormatterFilter) Reopen() error { return nil } +func (*hclogFormatterFilter) Reopen() error { return nil } // Type describes the type of the node as a Formatter. -func (_ *hclogFormatterFilter) Type() eventlogger.NodeType { +func (*hclogFormatterFilter) Type() eventlogger.NodeType { return eventlogger.NodeTypeFormatterFilter } // Name returns a representation of the HclogFormatter's name -func (_ *hclogFormatterFilter) Name() string { +func (*hclogFormatterFilter) Name() string { return hclogNodeName } diff --git a/internal/event/options_test.go b/internal/event/options_test.go index 80bd482bc..7a9916121 100644 --- a/internal/event/options_test.go +++ b/internal/event/options_test.go @@ -5,8 +5,8 @@ package event import ( "context" + "crypto/rand" "encoding/base64" - "math/rand" "net/url" "testing" "time" diff --git a/internal/event/telemetry_filter.go b/internal/event/telemetry_filter.go index d82927b48..8af9a0b62 100644 --- a/internal/event/telemetry_filter.go +++ b/internal/event/telemetry_filter.go @@ -121,7 +121,6 @@ func recurseStructureWithProtoFilter(value reflect.Value, filterFunc protoFilter sKind := sVal.Kind() if sKind == reflect.Ptr || sKind == reflect.Interface { sVal = sVal.Elem() - sKind = sVal.Kind() } if err := recurseStructureWithProtoFilter(sVal, filterFunc, isObservable); err != nil { return err diff --git a/internal/event/testing.go b/internal/event/testing.go index 8f4617b88..5e043071a 100644 --- a/internal/event/testing.go +++ b/internal/event/testing.go @@ -6,7 +6,7 @@ package event import ( "context" "encoding/json" - "io/ioutil" + "io" "os" "sync" "testing" @@ -59,7 +59,7 @@ func TestWithoutEventing(t testing.TB) *Eventer { testLock := &sync.Mutex{} testLogger := hclog.New(&hclog.LoggerOptions{ Mutex: testLock, - Output: ioutil.Discard, + Output: io.Discard, }) testEventer, err := NewEventer(testLogger, testLock, "TestWithoutEventing", testConfig, withNoDefaultSink(t)) require.NoError(err) @@ -95,10 +95,10 @@ type TestConfig struct { func TestEventerConfig(t testing.TB, testName string, opt ...Option) TestConfig { t.Helper() require := require.New(t) - tmpAllFile, err := ioutil.TempFile("./", "tmp-all-events-"+testName) + tmpAllFile, err := os.CreateTemp("./", "tmp-all-events-"+testName) require.NoError(err) - tmpErrFile, err := ioutil.TempFile("./", "tmp-errors-"+testName) + tmpErrFile, err := os.CreateTemp("./", "tmp-errors-"+testName) require.NoError(err) t.Cleanup(func() { @@ -153,7 +153,7 @@ func TestEventerConfig(t testing.TB, testName string, opt ...Option) TestConfig }) } if opts.withAuditSink { - tmpFile, err := ioutil.TempFile("./", "tmp-audit-"+testName) + tmpFile, err := os.CreateTemp("./", "tmp-audit-"+testName) require.NoError(err) t.Cleanup(func() { os.Remove(tmpFile.Name()) @@ -172,7 +172,7 @@ func TestEventerConfig(t testing.TB, testName string, opt ...Option) TestConfig c.AuditEvents = tmpFile } if opts.withObservationSink { - tmpFile, err := ioutil.TempFile("./", "tmp-observation-"+testName) + tmpFile, err := os.CreateTemp("./", "tmp-observation-"+testName) require.NoError(err) t.Cleanup(func() { os.Remove(tmpFile.Name()) @@ -190,7 +190,7 @@ func TestEventerConfig(t testing.TB, testName string, opt ...Option) TestConfig c.ObservationEvents = tmpFile } if opts.withSysSink { - tmpFile, err := ioutil.TempFile("./", "tmp-sysevents-"+testName) + tmpFile, err := os.CreateTemp("./", "tmp-sysevents-"+testName) require.NoError(err) t.Cleanup(func() { os.Remove(tmpFile.Name()) diff --git a/internal/host/host_dns_address.go b/internal/host/host_dns_address.go index 155ebb0c6..ef8e0d53b 100644 --- a/internal/host/host_dns_address.go +++ b/internal/host/host_dns_address.go @@ -54,22 +54,22 @@ func allocDnsName() DnsName { } // Clone an DnsName -func (c *DnsName) Clone() *DnsName { - cp := proto.Clone(c.DnsName) +func (dn *DnsName) Clone() *DnsName { + cp := proto.Clone(dn.DnsName) return &DnsName{ DnsName: cp.(*store.DnsName), } } // TableName returns the table name. -func (c *DnsName) TableName() string { - if c.tableName != "" { - return c.tableName +func (dn *DnsName) TableName() string { + if dn.tableName != "" { + return dn.tableName } return defaultDnsNameTableName } // SetTableName sets the table name. -func (c *DnsName) SetTableName(n string) { - c.tableName = n +func (dn *DnsName) SetTableName(n string) { + dn.tableName = n } diff --git a/internal/host/host_ip_address.go b/internal/host/host_ip_address.go index e07b80f6a..756f0ce88 100644 --- a/internal/host/host_ip_address.go +++ b/internal/host/host_ip_address.go @@ -59,22 +59,22 @@ func allocIpAddress() IpAddress { } // Clone an IpAddress -func (c *IpAddress) Clone() *IpAddress { - cp := proto.Clone(c.IpAddress) +func (ia *IpAddress) Clone() *IpAddress { + cp := proto.Clone(ia.IpAddress) return &IpAddress{ IpAddress: cp.(*store.IpAddress), } } // TableName returns the table name. -func (c *IpAddress) TableName() string { - if c.tableName != "" { - return c.tableName +func (ia *IpAddress) TableName() string { + if ia.tableName != "" { + return ia.tableName } return defaultIpAddressTableName } // SetTableName sets the table name. -func (c *IpAddress) SetTableName(n string) { - c.tableName = n +func (ia *IpAddress) SetTableName(n string) { + ia.tableName = n } diff --git a/internal/host/plugin/host.go b/internal/host/plugin/host.go index 23bd96713..36f3dab87 100644 --- a/internal/host/plugin/host.go +++ b/internal/host/plugin/host.go @@ -78,21 +78,21 @@ func (h *Host) GetAddress() string { } // TableName returns the table name for the host set. -func (s *Host) TableName() string { - if s.tableName != "" { - return s.tableName +func (h Host) TableName() string { + if h.tableName != "" { + return h.tableName } return "host_plugin_host" } // SetTableName sets the table name. If the caller attempts to // set the name to "" the name will be reset to the default name. -func (s *Host) SetTableName(n string) { - s.tableName = n +func (h *Host) SetTableName(n string) { + h.tableName = n } // GetResourceType returns the resource type of the Host -func (s *Host) GetResourceType() resource.Type { +func (h Host) GetResourceType() resource.Type { return resource.Host } diff --git a/internal/host/plugin/job_orphaned_host_cleanup.go b/internal/host/plugin/job_orphaned_host_cleanup.go index 3cde235f3..1206d286e 100644 --- a/internal/host/plugin/job_orphaned_host_cleanup.go +++ b/internal/host/plugin/job_orphaned_host_cleanup.go @@ -68,7 +68,7 @@ func (r *OrphanedHostCleanupJob) Status() scheduler.JobStatus { // will be returned. func (r *OrphanedHostCleanupJob) Run(ctx context.Context) error { const op = "plugin.(OrphanedHostCleanupJob).Run" - if !r.running.CAS(r.running.Load(), true) { + if !r.running.CompareAndSwap(r.running.Load(), true) { return errors.New(ctx, errors.JobAlreadyRunning, op, "job already running") } defer r.running.Store(false) diff --git a/internal/host/plugin/job_set_sync.go b/internal/host/plugin/job_set_sync.go index 56afe4898..a2428b197 100644 --- a/internal/host/plugin/job_set_sync.go +++ b/internal/host/plugin/job_set_sync.go @@ -87,7 +87,7 @@ func (r *SetSyncJob) Status() scheduler.JobStatus { // will be returned. func (r *SetSyncJob) Run(ctx context.Context) error { const op = "plugin.(SetSyncJob).Run" - if !r.running.CAS(r.running.Load(), true) { + if !r.running.CompareAndSwap(r.running.Load(), true) { return errors.New(ctx, errors.JobAlreadyRunning, op, "job already running") } defer r.running.Store(false) diff --git a/internal/host/plugin/repository_host_set.go b/internal/host/plugin/repository_host_set.go index 915ff12e9..c30c9f110 100644 --- a/internal/host/plugin/repository_host_set.go +++ b/internal/host/plugin/repository_host_set.go @@ -745,11 +745,11 @@ func (r *Repository) DeleteSet(ctx context.Context, projectId string, publicId s if err != nil { return 0, errors.Wrap(ctx, err, op) } - _, err = plgClient.OnDeleteSet(ctx, &plgpb.OnDeleteSetRequest{Catalog: plgHc, Persisted: p, Set: plgHs}) - if err != nil { - // Even if the plugin returns an error, we ignore it and proceed - // with deleting the set. - } + // Even if the plugin returns an error, we ignore it and proceed with + // deleting the set, hence we don't check the error here. This is because we + // may get errors from the plugin that we can't do anything about (say, it's + // already deleted) and we still want to delete the set from the database. + _, _ = plgClient.OnDeleteSet(ctx, &plgpb.OnDeleteSetRequest{Catalog: plgHc, Persisted: p, Set: plgHs}) oplogWrapper, err := r.kms.GetWrapper(ctx, projectId, kms.KeyPurposeOplog) if err != nil { diff --git a/internal/host/preferred_endpoint.go b/internal/host/preferred_endpoint.go index d35a39cf9..cbc9650e8 100644 --- a/internal/host/preferred_endpoint.go +++ b/internal/host/preferred_endpoint.go @@ -69,22 +69,22 @@ func AllocPreferredEndpoint() *PreferredEndpoint { } // Clone a PreferredEndpoint -func (c *PreferredEndpoint) Clone() *PreferredEndpoint { - cp := proto.Clone(c.PreferredEndpoint) +func (pe *PreferredEndpoint) Clone() *PreferredEndpoint { + cp := proto.Clone(pe.PreferredEndpoint) return &PreferredEndpoint{ PreferredEndpoint: cp.(*store.PreferredEndpoint), } } // TableName returns the table name. -func (c *PreferredEndpoint) TableName() string { - if c.tableName != "" { - return c.tableName +func (pe *PreferredEndpoint) TableName() string { + if pe.tableName != "" { + return pe.tableName } return defaultPreferredEndpointTableName } // SetTableName sets the table name. -func (c *PreferredEndpoint) SetTableName(n string) { - c.tableName = n +func (pe *PreferredEndpoint) SetTableName(n string) { + pe.tableName = n } diff --git a/internal/iam/repository_role_grant_test.go b/internal/iam/repository_role_grant_test.go index aa2bd754e..85f7cb5b9 100644 --- a/internal/iam/repository_role_grant_test.go +++ b/internal/iam/repository_role_grant_test.go @@ -440,9 +440,9 @@ func TestRepository_SetRoleGrants_Randomize(t *testing.T) { for i := 1; i <= totalCnt; i++ { grantsToSet = make([]string, 0, totalCnt) expected = make(map[string]bool, totalCnt) - rand.Seed(time.Now().UnixNano()) + prng := rand.New(rand.NewSource(time.Now().UnixNano())) for _, rgw := range grants { - rgw.enabled = rand.Int()%2 == 0 + rgw.enabled = prng.Int()%2 == 0 if rgw.enabled { grantsToSet = append(grantsToSet, rgw.grantString) expected[rgw.grantString] = true diff --git a/internal/iam/repository_scope_test.go b/internal/iam/repository_scope_test.go index e8c1ba532..902562def 100644 --- a/internal/iam/repository_scope_test.go +++ b/internal/iam/repository_scope_test.go @@ -9,7 +9,6 @@ import ( "testing" "time" - "github.com/golang/protobuf/ptypes" "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/db/timestamp" iam_store "github.com/hashicorp/boundary/internal/iam/store" @@ -18,6 +17,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" ) func Test_Repository_Scope_Create(t *testing.T) { @@ -270,7 +270,7 @@ func Test_Repository_Scope_Delete(t *testing.T) { func TestRepository_UpdateScope(t *testing.T) { conn, _ := db.TestSetup(t, "postgres") - now := ×tamp.Timestamp{Timestamp: ptypes.TimestampNow()} + now := ×tamp.Timestamp{Timestamp: timestamppb.Now()} id := testId(t) rw := db.New(conn) wrapper := db.TestWrapper(t) diff --git a/internal/iam/repository_test.go b/internal/iam/repository_test.go index d8567e600..73a5128c0 100644 --- a/internal/iam/repository_test.go +++ b/internal/iam/repository_test.go @@ -9,7 +9,6 @@ import ( "testing" "time" - "github.com/golang/protobuf/ptypes" "github.com/hashicorp/boundary/internal/db" "github.com/hashicorp/boundary/internal/db/timestamp" iam_store "github.com/hashicorp/boundary/internal/iam/store" @@ -20,6 +19,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" ) func TestNewRepository(t *testing.T) { @@ -178,7 +178,7 @@ func Test_Repository_delete(t *testing.T) { func TestRepository_update(t *testing.T) { conn, _ := db.TestSetup(t, "postgres") - now := ×tamp.Timestamp{Timestamp: ptypes.TimestampNow()} + now := ×tamp.Timestamp{Timestamp: timestamppb.Now()} id := testId(t) wrapper := db.TestWrapper(t) rw := db.New(conn) diff --git a/internal/kms/data_key_version_destruction_job.go b/internal/kms/data_key_version_destruction_job.go index 744343f1d..7cacd9b29 100644 --- a/internal/kms/data_key_version_destruction_job.go +++ b/internal/kms/data_key_version_destruction_job.go @@ -26,8 +26,8 @@ func allocDataKeyVersionDestructionJob() DataKeyVersionDestructionJob { } // Clone a DataKeyVersionDestructionJob -func (c *DataKeyVersionDestructionJob) Clone() *DataKeyVersionDestructionJob { - cp := proto.Clone(c.DataKeyVersionDestructionJob) +func (k *DataKeyVersionDestructionJob) Clone() *DataKeyVersionDestructionJob { + cp := proto.Clone(k.DataKeyVersionDestructionJob) return &DataKeyVersionDestructionJob{ DataKeyVersionDestructionJob: cp.(*store.DataKeyVersionDestructionJob), } diff --git a/internal/kms/data_key_version_destruction_job_progress.go b/internal/kms/data_key_version_destruction_job_progress.go index c3bda04e5..df82e80aa 100644 --- a/internal/kms/data_key_version_destruction_job_progress.go +++ b/internal/kms/data_key_version_destruction_job_progress.go @@ -26,8 +26,8 @@ func allocDataKeyVersionDestructionJobProgress() DataKeyVersionDestructionJobPro } // Clone an DataKeyVersionDestructionJob -func (c *DataKeyVersionDestructionJobProgress) Clone() *DataKeyVersionDestructionJobProgress { - cp := proto.Clone(c.DataKeyVersionDestructionJobProgress) +func (k *DataKeyVersionDestructionJobProgress) Clone() *DataKeyVersionDestructionJobProgress { + cp := proto.Clone(k.DataKeyVersionDestructionJobProgress) return &DataKeyVersionDestructionJobProgress{ DataKeyVersionDestructionJobProgress: cp.(*store.DataKeyVersionDestructionJobProgress), } diff --git a/internal/kms/data_key_version_destruction_job_run.go b/internal/kms/data_key_version_destruction_job_run.go index 18cd8b498..cad430a48 100644 --- a/internal/kms/data_key_version_destruction_job_run.go +++ b/internal/kms/data_key_version_destruction_job_run.go @@ -26,8 +26,8 @@ func allocDataKeyVersionDestructionJobRun() DataKeyVersionDestructionJobRun { } // Clone a DataKeyVersionDestructionJobRun -func (c *DataKeyVersionDestructionJobRun) Clone() *DataKeyVersionDestructionJobRun { - cp := proto.Clone(c.DataKeyVersionDestructionJobRun) +func (k *DataKeyVersionDestructionJobRun) Clone() *DataKeyVersionDestructionJobRun { + cp := proto.Clone(k.DataKeyVersionDestructionJobRun) return &DataKeyVersionDestructionJobRun{ DataKeyVersionDestructionJobRun: cp.(*store.DataKeyVersionDestructionJobRun), } diff --git a/internal/kms/data_key_version_destruction_job_run_allowed_table_name.go b/internal/kms/data_key_version_destruction_job_run_allowed_table_name.go index 40b524184..fec1b6e3b 100644 --- a/internal/kms/data_key_version_destruction_job_run_allowed_table_name.go +++ b/internal/kms/data_key_version_destruction_job_run_allowed_table_name.go @@ -26,8 +26,8 @@ func allocDataKeyVersionDestructionJobRunAllowedTableName() DataKeyVersionDestru } // Clone an DataKeyVersionDestructionJob -func (c *DataKeyVersionDestructionJobRunAllowedTableName) Clone() *DataKeyVersionDestructionJobRunAllowedTableName { - cp := proto.Clone(c.DataKeyVersionDestructionJobRunAllowedTableName) +func (k *DataKeyVersionDestructionJobRunAllowedTableName) Clone() *DataKeyVersionDestructionJobRunAllowedTableName { + cp := proto.Clone(k.DataKeyVersionDestructionJobRunAllowedTableName) return &DataKeyVersionDestructionJobRunAllowedTableName{ DataKeyVersionDestructionJobRunAllowedTableName: cp.(*store.DataKeyVersionDestructionJobRunAllowedTableName), } diff --git a/internal/kms/job/data_key_version_destruction_monitor_job.go b/internal/kms/job/data_key_version_destruction_monitor_job.go index 3d8028029..91be9ade8 100644 --- a/internal/kms/job/data_key_version_destruction_monitor_job.go +++ b/internal/kms/job/data_key_version_destruction_monitor_job.go @@ -29,7 +29,7 @@ func newDataKeyVersionDestructionMonitorJob(ctx context.Context, kmsRepo *kms.Km // Status reports the job’s current status. We never change these values as // this job never finishes. -func (d *dataKeyVersionDestructionMonitorJob) Status() scheduler.JobStatus { +func (r dataKeyVersionDestructionMonitorJob) Status() scheduler.JobStatus { return scheduler.JobStatus{} } @@ -53,11 +53,11 @@ func (r *dataKeyVersionDestructionMonitorJob) NextRunIn(_ context.Context) (time } // Name is the unique name of the job. -func (r *dataKeyVersionDestructionMonitorJob) Name() string { +func (r dataKeyVersionDestructionMonitorJob) Name() string { return "data-key-version-destruction-monitor-job" } // Description is the human readable description of the job. -func (d *dataKeyVersionDestructionMonitorJob) Description() string { +func (r dataKeyVersionDestructionMonitorJob) Description() string { return "Destroy a key version once all data has been rewrapped" } diff --git a/internal/kms/job/table_rewrapping_job.go b/internal/kms/job/table_rewrapping_job.go index 5f85b3c3a..116bd167c 100644 --- a/internal/kms/job/table_rewrapping_job.go +++ b/internal/kms/job/table_rewrapping_job.go @@ -35,7 +35,7 @@ func newTableRewrappingJob(ctx context.Context, kmsRepo *kms.Kms, tableName stri // Status reports the job’s current status. We never change these values as // this job never finishes. -func (d *tableRewrappingJob) Status() scheduler.JobStatus { +func (r tableRewrappingJob) Status() scheduler.JobStatus { return scheduler.JobStatus{} } @@ -54,16 +54,16 @@ func (r *tableRewrappingJob) Run(ctx context.Context) error { // NextRunIn returns the duration until the next job run should be scheduled. // We report as ready 1 second after a successful run. This doesn't mean that // this job will run every second, only about as often as the configured scheduler interval. -func (r *tableRewrappingJob) NextRunIn(_ context.Context) (time.Duration, error) { +func (r tableRewrappingJob) NextRunIn(_ context.Context) (time.Duration, error) { return time.Second, nil } // Name is the unique name of the job. -func (r *tableRewrappingJob) Name() string { +func (r tableRewrappingJob) Name() string { return fmt.Sprintf("%s-rewrapping-job", r.tableName) } // Description is the human readable description of the job. -func (d *tableRewrappingJob) Description() string { +func (r tableRewrappingJob) Description() string { return "Re-encrypt all data encrypted in a table using a specific key" } diff --git a/internal/oplog/immutable_fields_test.go b/internal/oplog/immutable_fields_test.go index cdd826f0f..6cce400aa 100644 --- a/internal/oplog/immutable_fields_test.go +++ b/internal/oplog/immutable_fields_test.go @@ -8,7 +8,6 @@ import ( "testing" "time" - "github.com/golang/protobuf/ptypes" "github.com/hashicorp/boundary/internal/db/timestamp" "github.com/hashicorp/boundary/internal/oplog/oplog_test" "github.com/hashicorp/boundary/internal/oplog/store" @@ -16,6 +15,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" ) func Test_ImmutableFields(t *testing.T) { @@ -58,8 +58,7 @@ func Test_ImmutableFields(t *testing.T) { &Message{Message: &u2, TypeName: "user", OpType: OpType_OP_TYPE_CREATE}) require.NoError(t, err) - future, err := ptypes.TimestampProto(time.Now().Add(time.Hour)) - require.NoError(t, err) + future := timestamppb.New(time.Now().Add(time.Hour)) tests := []struct { name string diff --git a/internal/oplog/oplog.go b/internal/oplog/oplog.go index 7fd43af00..808266969 100644 --- a/internal/oplog/oplog.go +++ b/internal/oplog/oplog.go @@ -197,6 +197,9 @@ func convertToDbwOpts(ctx context.Context, opts *OperationOptions) ([]dbw.Option for _, a := range pbVal.ExprValue.GetArgs() { args = append(args, a.AsInterface()) } + if len(args) > 0 { + expr.Vars = args + } newColVal.Value = expr case *ColumnValue_Column: newColVal.Value = dbw.Column{ diff --git a/internal/scheduler/scheduler.go b/internal/scheduler/scheduler.go index 08e5c4d43..50ad3e82b 100644 --- a/internal/scheduler/scheduler.go +++ b/internal/scheduler/scheduler.go @@ -136,7 +136,7 @@ func (s *Scheduler) UpdateJobNextRunInAtLeast(ctx context.Context, name string, // need to be instantiated in order to begin scheduling again. func (s *Scheduler) Start(ctx context.Context, wg *sync.WaitGroup) error { const op = "scheduler.(Scheduler).Start" - if !s.started.CAS(s.started.Load(), true) { + if !s.started.CompareAndSwap(s.started.Load(), true) { event.WriteSysEvent(ctx, op, "scheduler already started, skipping") return nil } diff --git a/internal/server/repository_workerauth.go b/internal/server/repository_workerauth.go index d9c2ebbaa..05e12ec78 100644 --- a/internal/server/repository_workerauth.go +++ b/internal/server/repository_workerauth.go @@ -24,7 +24,6 @@ import ( "github.com/hashicorp/boundary/internal/util" "github.com/hashicorp/go-dbw" "github.com/hashicorp/nodeenrollment" - nodee "github.com/hashicorp/nodeenrollment" "github.com/hashicorp/nodeenrollment/types" "github.com/mitchellh/mapstructure" "google.golang.org/protobuf/proto" @@ -32,7 +31,7 @@ import ( // Ensure we implement the Storage interfaces var ( - _ nodee.Storage = (*WorkerAuthRepositoryStorage)(nil) + _ nodeenrollment.Storage = (*WorkerAuthRepositoryStorage)(nil) ) type rootCertificatesVersion struct { @@ -68,7 +67,7 @@ func NewRepositoryStorage(ctx context.Context, r db.Reader, w db.Writer, kms *km } // Store implements the Storage interface -func (r *WorkerAuthRepositoryStorage) Store(ctx context.Context, msg nodee.MessageWithId) error { +func (r *WorkerAuthRepositoryStorage) Store(ctx context.Context, msg nodeenrollment.MessageWithId) error { const op = "server.(WorkerAuthRepositoryStorage).Store" if err := types.ValidateMessage(msg); err != nil { return errors.Wrap(ctx, err, op) @@ -426,7 +425,7 @@ func (r *WorkerAuthRepositoryStorage) storeRootCertificates(ctx context.Context, // Load implements the Storage interface. // Load loads values into the given message. The message must be populated // with the ID value. If not found, the returned error should be ErrNotFound. -func (r *WorkerAuthRepositoryStorage) Load(ctx context.Context, msg nodee.MessageWithId) error { +func (r *WorkerAuthRepositoryStorage) Load(ctx context.Context, msg nodeenrollment.MessageWithId) error { const op = "server.(WorkerAuthRepositoryStorage).Load" if err := types.ValidateMessage(msg); err != nil { return errors.Wrap(ctx, err, op) @@ -493,13 +492,13 @@ func (r *WorkerAuthRepositoryStorage) loadNodeInformation(ctx context.Context, n workerAuthorizedSet, err := r.validateWorkerAuths(ctx, workerAuths) if err != nil { if errors.IsNotFoundError(err) { - return nodee.ErrNotFound + return nodeenrollment.ErrNotFound } return errors.Wrap(ctx, err, op) } if workerAuthorizedSet == nil || workerAuthorizedSet.Current == nil { - return nodee.ErrNotFound + return nodeenrollment.ErrNotFound } if workerAuthorizedSet.Previous != nil { @@ -566,7 +565,7 @@ func (r *WorkerAuthRepositoryStorage) loadServerLedActivationToken(ctx context.C err := r.reader.LookupWhere(ctx, activationTokenEntry, "token_id = ?", []any{token.Id}) if err != nil { if errors.Is(err, dbw.ErrRecordNotFound) { - return nodee.ErrNotFound + return nodeenrollment.ErrNotFound } return errors.Wrap(ctx, err, op) } @@ -663,7 +662,7 @@ func (r *WorkerAuthRepositoryStorage) loadRootCertificates(ctx context.Context, } err := r.reader.LookupById(ctx, certAuthority) if err != nil { - return nodee.ErrNotFound + return nodeenrollment.ErrNotFound } // Add version to state field of cert @@ -687,7 +686,7 @@ func (r *WorkerAuthRepositoryStorage) loadRootCertificates(ctx context.Context, } if rootCertificate.Certificate == nil { - return nodee.ErrNotFound + return nodeenrollment.ErrNotFound } // decrypt private key @@ -719,7 +718,7 @@ func (r *WorkerAuthRepositoryStorage) loadRootCertificates(ctx context.Context, // Remove implements the Storage interface. // Remove removes the given message. Only the ID field of the message is considered. -func (r *WorkerAuthRepositoryStorage) Remove(ctx context.Context, msg nodee.MessageWithId) error { +func (r *WorkerAuthRepositoryStorage) Remove(ctx context.Context, msg nodeenrollment.MessageWithId) error { const op = "server.(WorkerAuthRepositoryStorage).Remove" if err := types.ValidateMessage(msg); err != nil { return errors.New(ctx, errors.InvalidParameter, op, "given message cannot be removed as it has no ID") diff --git a/internal/server/repository_workerauth_test.go b/internal/server/repository_workerauth_test.go index 97295a5b7..a9636080e 100644 --- a/internal/server/repository_workerauth_test.go +++ b/internal/server/repository_workerauth_test.go @@ -21,7 +21,6 @@ import ( "github.com/hashicorp/boundary/internal/types/scope" wrapping "github.com/hashicorp/go-kms-wrapping/v2" "github.com/hashicorp/nodeenrollment" - nodee "github.com/hashicorp/nodeenrollment" "github.com/hashicorp/nodeenrollment/registration" "github.com/hashicorp/nodeenrollment/rotation" "github.com/hashicorp/nodeenrollment/storage/file" @@ -201,7 +200,7 @@ func TestStoreWorkerAuth(t *testing.T) { Id: keyId, } err = storage.Load(ctx, nodeLookup) - assert.Equal(err, nodee.ErrNotFound) + assert.Equal(err, nodeenrollment.ErrNotFound) // The AuthorizeNode request will result in a WorkerAuth record being stored _, err = registration.AuthorizeNode(ctx, storage, fetchReq, nodeenrollment.WithState(state)) diff --git a/internal/server/root_certificate.go b/internal/server/root_certificate.go index 6e06b4ac2..1b8ea837d 100644 --- a/internal/server/root_certificate.go +++ b/internal/server/root_certificate.go @@ -89,7 +89,7 @@ func newRootCertificate(ctx context.Context, serialNumber uint64, certificate [] ) (*RootCertificate, error) { const op = "server.newRootCertificate" - if &serialNumber == nil { + if serialNumber == 0 { return nil, errors.New(ctx, errors.InvalidParameter, op, "no serialNumber") } if certificate == nil || len(certificate) == 0 { @@ -146,7 +146,7 @@ func (r *RootCertificate) clone() *RootCertificate { // Validate the RootCertificate. On success, return nil func (r *RootCertificate) ValidateNewRootCertificate(ctx context.Context) error { const op = "server.(RootCertificate).ValidateNewRootCertificate" - if &r.SerialNumber == nil { + if r.SerialNumber == 0 { return errors.New(ctx, errors.InvalidParameter, op, "missing SerialNumber") } if r.Certificate == nil { diff --git a/internal/server/worker_auth.go b/internal/server/worker_auth.go index 3a7bce2e6..08b91c3f4 100644 --- a/internal/server/worker_auth.go +++ b/internal/server/worker_auth.go @@ -102,11 +102,12 @@ func newWorkerAuth(ctx context.Context, workerKeyIdentifier, workerId string, op }, } - if &opts.withWorkerKeys != nil { + if len(opts.withWorkerKeys.workerSigningPubKey) != 0 && + len(opts.withWorkerKeys.workerEncryptionPubKey) != 0 { l.WorkerSigningPubKey = opts.withWorkerKeys.workerSigningPubKey l.WorkerEncryptionPubKey = opts.withWorkerKeys.workerEncryptionPubKey } - if &opts.withControllerEncryptionPrivateKey != nil { + if len(opts.withControllerEncryptionPrivateKey) != 0 { l.ControllerEncryptionPrivKey = opts.withControllerEncryptionPrivateKey } if opts.withNonce != nil { diff --git a/internal/server/worker_tags_test.go b/internal/server/worker_tags_test.go index a18809bac..181580915 100644 --- a/internal/server/worker_tags_test.go +++ b/internal/server/worker_tags_test.go @@ -674,7 +674,7 @@ func TestRepository_WorkerTagsConsequent(t *testing.T) { assert.Contains(worker.apiTags, &Tag{Key: "key2", Value: "value2"}) // Add another valid tag to worker - added, err = repo.AddWorkerTags(context.Background(), worker.PublicId, worker.Version, []*Tag{ + _, err = repo.AddWorkerTags(context.Background(), worker.PublicId, worker.Version, []*Tag{ {Key: "key!", Value: "value!"}, }) assert.NoError(err) @@ -706,7 +706,7 @@ func TestRepository_WorkerTagsConsequent(t *testing.T) { assert.Equal(4, len(worker.configTags)) // Go full circle - added, err = repo.AddWorkerTags(context.Background(), worker.PublicId, worker.Version, manyTags) + _, err = repo.AddWorkerTags(context.Background(), worker.PublicId, worker.Version, manyTags) assert.NoError(err) worker, err = repo.LookupWorker(context.Background(), worker.PublicId) require.NoError(err) diff --git a/internal/session/repository_session_test.go b/internal/session/repository_session_test.go index befb4d81b..be1062c4f 100644 --- a/internal/session/repository_session_test.go +++ b/internal/session/repository_session_test.go @@ -917,6 +917,7 @@ func TestRepository_TerminateCompletedSessions(t *testing.T) { iamRepo := iam.TestRepo(t, conn, wrapper) kms := kms.TestKms(t, conn, wrapper) repo, err := NewRepository(ctx, rw, rw, kms) + require.NoError(t, err) connRepo, err := NewConnectionRepository(ctx, rw, rw, kms) require.NoError(t, err) diff --git a/internal/types/action/action.go b/internal/types/action/action.go index f5045182b..eb99b4c79 100644 --- a/internal/types/action/action.go +++ b/internal/types/action/action.go @@ -226,11 +226,11 @@ func (a Type) String() string { // IsActionOrParent tests whether the given action is either the same as the // suspect or is a parent of the suspect. This is used in some parts of ACL // checking. -func (act Type) IsActionOrParent(suspect Type) bool { - if act == suspect { +func (a Type) IsActionOrParent(suspect Type) bool { + if a == suspect { return true } - return strings.HasPrefix(suspect.String(), fmt.Sprintf("%s:", act.String())) + return strings.HasPrefix(suspect.String(), fmt.Sprintf("%s:", a.String())) } // ActionSet is a set of action.Type. diff --git a/internal/website/permstable/permstable.go b/internal/website/permstable/permstable.go index f001e0bb8..65ea67181 100644 --- a/internal/website/permstable/permstable.go +++ b/internal/website/permstable/permstable.go @@ -948,9 +948,7 @@ var worker = &Resource{ "ID": "", "Type": "worker", }, - Actions: append( - rudActions("a worker", false), - ), + Actions: rudActions("a worker", false), }, }, } diff --git a/testing/dbtest/session_list_benchmarks_dump_generation_test.go b/testing/dbtest/session_list_benchmarks_dump_generation_test.go index 1a87be006..f5d9c6d35 100644 --- a/testing/dbtest/session_list_benchmarks_dump_generation_test.go +++ b/testing/dbtest/session_list_benchmarks_dump_generation_test.go @@ -226,7 +226,7 @@ func cycleSessionStates(t testing.TB, ctx context.Context, sess *session.Session } // Cancel 50% of the sessions if rand.Intn(2) == 0 { - sess, err = sessRepo.CancelSession(ctx, sess.PublicId, sess.Version) + _, err = sessRepo.CancelSession(ctx, sess.PublicId, sess.Version) require.NoError(t, err) _, err = session.CloseConnections(ctx, sessRepo, connRepo, closeWiths) require.NoError(t, err) diff --git a/testing/dbtest/template.go b/testing/dbtest/template.go index 3e4beaaa9..538e4dc19 100644 --- a/testing/dbtest/template.go +++ b/testing/dbtest/template.go @@ -9,7 +9,6 @@ import ( "fmt" "math/rand" "os" - "time" // postgres dialect @@ -25,8 +24,6 @@ var ( ) func init() { - rand.Seed(time.Now().UnixNano()) - p := os.Getenv("TEST_DB_PORT") if p != "" { testDBPort = p