From 141225baad7da90d28f521011b4bd05a2c04990f Mon Sep 17 00:00:00 2001 From: Andrew Gaffney Date: Mon, 5 May 2025 14:07:45 -0400 Subject: [PATCH] feat(credential/static): Implement UsernamePasswordDomain type (#1512) Co-authored-by: April-May <18632637+AprilMay0@users.noreply.github.com> --- globals/prefixes.go | 7 + internal/credential/credential.go | 8 + internal/credential/public_ids.go | 15 ++ internal/credential/static/query.go | 64 +++-- internal/credential/static/rewrapping.go | 46 ++++ internal/credential/static/rewrapping_test.go | 64 +++++ internal/credential/static/store/static.pb.go | 254 ++++++++++++++++-- .../usernamepassworddomain_credential.go | 145 ++++++++++ .../usernamepassworddomain_credential_test.go | 228 ++++++++++++++++ .../credential/static/store/v1/static.proto | 79 ++++++ 10 files changed, 855 insertions(+), 55 deletions(-) create mode 100644 internal/credential/static/usernamepassworddomain_credential.go create mode 100644 internal/credential/static/usernamepassworddomain_credential_test.go diff --git a/globals/prefixes.go b/globals/prefixes.go index 16f62265e..bb63cbbef 100644 --- a/globals/prefixes.go +++ b/globals/prefixes.go @@ -75,6 +75,9 @@ const ( // UsernamePasswordCredentialPrefix is the prefix for username/password // creds UsernamePasswordCredentialPrefix = "credup" + // UsernamePasswordDomainCredentialPrefix is the prefix for username/password/domain + // creds + UsernamePasswordDomainCredentialPrefix = "credupd" // UsernamePasswordCredentialPreviousPrefix is the previous prefix for // username/password creds UsernamePasswordCredentialPreviousPrefix = "cred" @@ -244,6 +247,10 @@ var prefixToResourceType = map[string]ResourceInfo{ Type: resource.Credential, Subtype: UnknownSubtype, }, + UsernamePasswordDomainCredentialPrefix: { + Type: resource.Credential, + Subtype: UnknownSubtype, + }, UsernamePasswordCredentialPreviousPrefix: { Type: resource.Credential, Subtype: UnknownSubtype, diff --git a/internal/credential/credential.go b/internal/credential/credential.go index d3813882a..03bf3d5c5 100644 --- a/internal/credential/credential.go +++ b/internal/credential/credential.go @@ -135,6 +135,14 @@ type UsernamePassword interface { Password() Password } +// UsernamePasswordDomain is a credential containing a username, a password, and a domain. +type UsernamePasswordDomain interface { + Credential + Username() string + Password() Password + Domain() string +} + // SshPrivateKey is a credential containing a username an SSH private key and // an optional private key passphrase. type SshPrivateKey interface { diff --git a/internal/credential/public_ids.go b/internal/credential/public_ids.go index 291e34d0d..0a9dcc928 100644 --- a/internal/credential/public_ids.go +++ b/internal/credential/public_ids.go @@ -14,6 +14,7 @@ import ( func init() { globals.RegisterPrefixToResourceInfo(globals.UsernamePasswordCredentialPrefix, resource.Credential, Domain, UsernamePasswordSubtype) + globals.RegisterPrefixToResourceInfo(globals.UsernamePasswordDomainCredentialPrefix, resource.Credential, Domain, UsernamePasswordDomainSubtype) globals.RegisterPrefixToResourceInfo(globals.UsernamePasswordCredentialPreviousPrefix, resource.Credential, Domain, UsernamePasswordSubtype) globals.RegisterPrefixToResourceInfo(globals.SshPrivateKeyCredentialPrefix, resource.Credential, Domain, SshPrivateKeySubtype) globals.RegisterPrefixToResourceInfo(globals.JsonCredentialPrefix, resource.Credential, Domain, JsonSubtype) @@ -22,11 +23,14 @@ func init() { const ( UsernamePasswordSubtype = globals.Subtype("username_password") + UsernamePasswordDomainSubtype = globals.Subtype("username_password_domain") + SshPrivateKeySubtype = globals.Subtype("ssh_private_key") JsonSubtype = globals.Subtype("json") ) +// NewUsernamePasswordCredentialId generates a new public ID for a username-password credential. func NewUsernamePasswordCredentialId(ctx context.Context) (string, error) { id, err := db.NewPublicId(ctx, globals.UsernamePasswordCredentialPrefix) if err != nil { @@ -35,6 +39,16 @@ func NewUsernamePasswordCredentialId(ctx context.Context) (string, error) { return id, nil } +// NewUsernamePasswordDomainCredentialId creates a new public ID for a username-password-domain credential. +func NewUsernamePasswordDomainCredentialId(ctx context.Context) (string, error) { + id, err := db.NewPublicId(ctx, globals.UsernamePasswordDomainCredentialPrefix) + if err != nil { + return "", errors.Wrap(ctx, err, "credential.NewUsernamePasswordDomainCredentialId") + } + return id, nil +} + +// New SshPrivateKeyCredentialId generates a new public ID for an SSH private key credential. func NewSshPrivateKeyCredentialId(ctx context.Context) (string, error) { id, err := db.NewPublicId(ctx, globals.SshPrivateKeyCredentialPrefix) if err != nil { @@ -43,6 +57,7 @@ func NewSshPrivateKeyCredentialId(ctx context.Context) (string, error) { return id, nil } +// NewJsonCredentialId creates a new public ID for a JSON credential. func NewJsonCredentialId(ctx context.Context) (string, error) { id, err := db.NewPublicId(ctx, globals.JsonCredentialPrefix) if err != nil { diff --git a/internal/credential/static/query.go b/internal/credential/static/query.go index 787872b86..3f9886e6c 100644 --- a/internal/credential/static/query.go +++ b/internal/credential/static/query.go @@ -5,40 +5,48 @@ package static const ( credStaticUsernamePasswordRewrapQuery = ` -select distinct - userpass.public_id, - userpass.password_encrypted, - userpass.key_id -from credential_static_username_password_credential userpass - inner join credential_static_store store - on store.public_id = userpass.store_id -where store.project_id = ? - and userpass.key_id = ?; +select distinct userpass.public_id, + userpass.password_encrypted, + userpass.key_id + from credential_static_username_password_credential userpass + inner join credential_static_store store + on store.public_id = userpass.store_id + where store.project_id = ? + and userpass.key_id = ?; +` + + credStaticUsernamePasswordDomainRewrapQuery = ` +select distinct upd.public_id, + upd.password_encrypted, + upd.key_id + from credential_static_username_password_domain_credential upd + inner join credential_static_store store + on store.public_id = upd.store_id + where store.project_id = ? + and upd.key_id = ?; ` credStaticSshPrivKeyRewrapQuery = ` -select distinct - ssh.public_id, - ssh.private_key_encrypted, - ssh.private_key_passphrase_encrypted, - ssh.key_id -from credential_static_ssh_private_key_credential ssh - inner join credential_static_store store - on store.public_id = ssh.store_id -where store.project_id = ? - and ssh.key_id = ?; +select distinct ssh.public_id, + ssh.private_key_encrypted, + ssh.private_key_passphrase_encrypted, + ssh.key_id + from credential_static_ssh_private_key_credential ssh + inner join credential_static_store store + on store.public_id = ssh.store_id + where store.project_id = ? + and ssh.key_id = ?; ` credStaticJsonRewrapQuery = ` -select distinct - json.public_id, - json.object_encrypted, - json.key_id -from credential_static_json_credential json - inner join credential_static_store store - on store.public_id = json.store_id -where store.project_id = ? - and json.key_id = ?; +select distinct json.public_id, + json.object_encrypted, + json.key_id + from credential_static_json_credential json + inner join credential_static_store store + on store.public_id = json.store_id + where store.project_id = ? + and json.key_id = ?; ` estimateCountCredentials = ` diff --git a/internal/credential/static/rewrapping.go b/internal/credential/static/rewrapping.go index 5aef39985..d8f278480 100644 --- a/internal/credential/static/rewrapping.go +++ b/internal/credential/static/rewrapping.go @@ -16,6 +16,7 @@ func init() { kms.RegisterTableRewrapFn("credential_static_username_password_credential", credStaticUsernamePasswordRewrapFn) kms.RegisterTableRewrapFn("credential_static_ssh_private_key_credential", credStaticSshPrivKeyRewrapFn) kms.RegisterTableRewrapFn("credential_static_json_credential", credStaticJsonRewrapFn) + kms.RegisterTableRewrapFn("credential_static_username_password_domain_credential", credStaticUsernamePasswordDomainRewrapFn) } func rewrapParameterChecks(ctx context.Context, dataKeyVersionId string, scopeId string, reader db.Reader, writer db.Writer, kmsRepo kms.GetWrapperer) string { @@ -82,6 +83,51 @@ func credStaticUsernamePasswordRewrapFn(ctx context.Context, dataKeyVersionId, s return nil } +func credStaticUsernamePasswordDomainRewrapFn(ctx context.Context, dataKeyVersionId, scopeId string, reader db.Reader, writer db.Writer, kmsRepo kms.GetWrapperer) error { + const op = "static.credStaticUsernamePasswordDomainRewrapFn" + if errStr := rewrapParameterChecks(ctx, dataKeyVersionId, scopeId, reader, writer, kmsRepo); errStr != "" { + return errors.New(ctx, errors.InvalidParameter, op, errStr) + } + var creds []*UsernamePasswordDomainCredential + // Indexes exist on (store_id, etc), so we can query static stores via scope and refine with key id. + // This is the fastest query we can use without creating a new index on key_id. + rows, err := reader.Query(ctx, credStaticUsernamePasswordDomainRewrapQuery, []any{scopeId, dataKeyVersionId}) + if err != nil { + return errors.Wrap(ctx, err, op, errors.WithMsg("failed to query sql for rows that need rewrapping")) + } + defer rows.Close() + for rows.Next() { + cred := allocUsernamePasswordDomainCredential() + if err := rows.Scan( + &cred.PublicId, + &cred.CtPassword, + &cred.KeyId, + ); err != nil { + return errors.Wrap(ctx, err, op, errors.WithMsg("failed to failed to scan row")) + } + creds = append(creds, cred) + } + if err := rows.Err(); err != nil { + return errors.Wrap(ctx, err, op, errors.WithMsg("failed to iterate over retrieved rows")) + } + wrapper, err := kmsRepo.GetWrapper(ctx, scopeId, kms.KeyPurposeDatabase) + if err != nil { + return errors.Wrap(ctx, err, op, errors.WithMsg("failed to fetch kms wrapper for rewrapping")) + } + for _, cred := range creds { + if err := cred.decrypt(ctx, wrapper); err != nil { + return errors.Wrap(ctx, err, op, errors.WithMsg("failed to decrypt username/password/domain credential")) + } + if err := cred.encrypt(ctx, wrapper); err != nil { + return errors.Wrap(ctx, err, op, errors.WithMsg("failed to re-encrypt username/password/domain credential")) + } + if _, err := writer.Update(ctx, cred, []string{"CtPassword", "KeyId"}, nil); err != nil { + return errors.Wrap(ctx, err, op, errors.WithMsg("failed to update username/password/domain credential row with rewrapped fields")) + } + } + return nil +} + func credStaticSshPrivKeyRewrapFn(ctx context.Context, dataKeyVersionId, scopeId string, reader db.Reader, writer db.Writer, kmsRepo kms.GetWrapperer) error { const op = "static.credStaticSshPrivKeyRewrapFn" if errStr := rewrapParameterChecks(ctx, dataKeyVersionId, scopeId, reader, writer, kmsRepo); errStr != "" { diff --git a/internal/credential/static/rewrapping_test.go b/internal/credential/static/rewrapping_test.go index b3f66cf92..e0610b779 100644 --- a/internal/credential/static/rewrapping_test.go +++ b/internal/credential/static/rewrapping_test.go @@ -256,3 +256,67 @@ func TestRewrap_credStaticJsonRewrapFn(t *testing.T) { assert.Equal(t, cred.GetObjectHmac(), got.GetObjectHmac()) }) } + +func TestRewrap_credStaticUsernamePasswordDomainRewrapFn(t *testing.T) { + ctx := context.Background() + t.Run("errors-on-query-error", func(t *testing.T) { + conn, mock := db.TestSetupWithMock(t) + wrapper := db.TestWrapper(t) + mock.ExpectQuery( + `SELECT \* FROM "kms_schema_version" WHERE 1=1 ORDER BY "kms_schema_version"\."version" LIMIT \$1`, + ).WillReturnRows(sqlmock.NewRows([]string{"version", "create_time"}).AddRow(migrations.Version, time.Now())) + mock.ExpectQuery( + `SELECT \* FROM "kms_oplog_schema_version" WHERE 1=1 ORDER BY "kms_oplog_schema_version"."version" LIMIT \$1`, + ).WillReturnRows(sqlmock.NewRows([]string{"version", "create_time"}).AddRow(migrations.Version, time.Now())) + kmsCache := kms.TestKms(t, conn, wrapper) + rw := db.New(conn) + mock.ExpectQuery( + `select distinct upd\.public_id, upd\.password_encrypted, upd\.key_id from credential_static_username_password_credential upd inner join credential_static_store store on store\.public_id = upd\.store_id where store\.project_id = \$1 and upd\.key_id = \$2;`, + ).WillReturnError(errors.New("Query error")) + err := credStaticUsernamePasswordDomainRewrapFn(ctx, "some_id", "some_scope", rw, rw, kmsCache) + require.Error(t, err) + }) + t.Run("success", func(t *testing.T) { + conn, _ := db.TestSetup(t, "postgres") + wrapper := db.TestWrapper(t) + kmsCache := kms.TestKms(t, conn, wrapper) + rw := db.New(conn) + + _, prj := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper)) + cs := TestCredentialStore(t, conn, wrapper, prj.PublicId) + cred, err := NewUsernamePasswordDomainCredential(cs.GetPublicId(), "username", "domain", "password") + assert.NoError(t, err) + + cred.PublicId, err = credential.NewUsernamePasswordCredentialId(ctx) + assert.NoError(t, err) + + kmsWrapper, err := kmsCache.GetWrapper(context.Background(), prj.PublicId, kms.KeyPurposeDatabase) + assert.NoError(t, err) + + assert.NoError(t, cred.encrypt(ctx, kmsWrapper)) + assert.NoError(t, rw.Create(context.Background(), cred)) + + // now things are stored in the db, we can rotate and rewrap + assert.NoError(t, kmsCache.RotateKeys(ctx, prj.PublicId)) + assert.NoError(t, credStaticUsernamePasswordDomainRewrapFn(ctx, cred.GetKeyId(), prj.PublicId, rw, rw, kmsCache)) + + // now we pull the credential back from the db, decrypt it with the new key, and ensure things match + got := allocUsernamePasswordDomainCredential() + got.PublicId = cred.PublicId + assert.NoError(t, rw.LookupById(ctx, got)) + + kmsWrapper2, err := kmsCache.GetWrapper(context.Background(), prj.PublicId, kms.KeyPurposeDatabase, kms.WithKeyId(got.GetKeyId())) + assert.NoError(t, err) + newKeyVersionId, err := kmsWrapper2.KeyId(ctx) + assert.NoError(t, err) + + // decrypt with the new key version and check to make sure things match + assert.NoError(t, got.decrypt(ctx, kmsWrapper2)) + assert.NotEmpty(t, got.GetKeyId()) + assert.NotEqual(t, cred.GetKeyId(), got.GetKeyId()) + assert.Equal(t, newKeyVersionId, got.GetKeyId()) + assert.Equal(t, "password", string(got.GetPassword())) + assert.NotEmpty(t, got.GetPasswordHmac()) + assert.Equal(t, cred.GetPasswordHmac(), got.GetPasswordHmac()) + }) +} diff --git a/internal/credential/static/store/static.pb.go b/internal/credential/static/store/static.pb.go index 520c7fab5..e7ae7b8fe 100644 --- a/internal/credential/static/store/static.pb.go +++ b/internal/credential/static/store/static.pb.go @@ -298,6 +298,179 @@ func (x *UsernamePasswordCredential) GetKeyId() string { return "" } +type UsernamePasswordDomainCredential struct { + state protoimpl.MessageState `protogen:"open.v1"` + // public_id is a surrogate key suitable for use in a public API. + // @inject_tag: `gorm:"primary_key"` + PublicId string `protobuf:"bytes,1,opt,name=public_id,json=publicId,proto3" json:"public_id,omitempty" gorm:"primary_key"` + // create_time is set by the database. + // @inject_tag: `gorm:"default:current_timestamp"` + CreateTime *timestamp.Timestamp `protobuf:"bytes,2,opt,name=create_time,json=createTime,proto3" json:"create_time,omitempty" gorm:"default:current_timestamp"` + // update_time is set by the database. + // @inject_tag: `gorm:"default:current_timestamp"` + UpdateTime *timestamp.Timestamp `protobuf:"bytes,3,opt,name=update_time,json=updateTime,proto3" json:"update_time,omitempty" gorm:"default:current_timestamp"` + // name is optional. If set, it must be unique within project_id. + // @inject_tag: `gorm:"default:null"` + Name string `protobuf:"bytes,4,opt,name=name,proto3" json:"name,omitempty" gorm:"default:null"` + // description is optional. + // @inject_tag: `gorm:"default:null"` + Description string `protobuf:"bytes,5,opt,name=description,proto3" json:"description,omitempty" gorm:"default:null"` + // store_id of the owning static credential store. + // It must be set. + // @inject_tag: `gorm:"not_null"` + StoreId string `protobuf:"bytes,6,opt,name=store_id,json=storeId,proto3" json:"store_id,omitempty" gorm:"not_null"` + // version allows optimistic locking of the resource. + // @inject_tag: `gorm:"default:null"` + Version uint32 `protobuf:"varint,7,opt,name=version,proto3" json:"version,omitempty" gorm:"default:null"` + // username is the username associated with the credential. + // It must be set. + // @inject_tag: `gorm:"not_null"` + Username string `protobuf:"bytes,8,opt,name=username,proto3" json:"username,omitempty" gorm:"not_null"` + // password is the plain-text of the password associated with the credential. We are + // not storing this plain-text password in the database. + // @inject_tag: `gorm:"-" wrapping:"pt,password_data"` + Password []byte `protobuf:"bytes,9,opt,name=password,proto3" json:"password,omitempty" gorm:"-" wrapping:"pt,password_data"` + // ct_password is the ciphertext of the password. It + // is stored in the database. + // @inject_tag: `gorm:"column:password_encrypted;not_null" wrapping:"ct,password_data"` + CtPassword []byte `protobuf:"bytes,10,opt,name=ct_password,json=ctPassword,proto3" json:"ct_password,omitempty" gorm:"column:password_encrypted;not_null" wrapping:"ct,password_data"` + // password_hmac is a sha256-hmac of the unencrypted password. It is recalculated + // everytime the password is updated. + // @inject_tag: `gorm:"not_null"` + PasswordHmac []byte `protobuf:"bytes,11,opt,name=password_hmac,json=passwordHmac,proto3" json:"password_hmac,omitempty" gorm:"not_null"` + // The key_id of the kms database key used for encrypting this entry. + // It must be set. + // @inject_tag: `gorm:"not_null"` + KeyId string `protobuf:"bytes,12,opt,name=key_id,json=keyId,proto3" json:"key_id,omitempty" gorm:"not_null"` + // Domain is the domain associated with the credential.. + // It must be set. + // @inject_tag: `gorm:"not_null"` + Domain string `protobuf:"bytes,13,opt,name=domain,proto3" json:"domain,omitempty" gorm:"not_null"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UsernamePasswordDomainCredential) Reset() { + *x = UsernamePasswordDomainCredential{} + mi := &file_controller_storage_credential_static_store_v1_static_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UsernamePasswordDomainCredential) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UsernamePasswordDomainCredential) ProtoMessage() {} + +func (x *UsernamePasswordDomainCredential) ProtoReflect() protoreflect.Message { + mi := &file_controller_storage_credential_static_store_v1_static_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UsernamePasswordDomainCredential.ProtoReflect.Descriptor instead. +func (*UsernamePasswordDomainCredential) Descriptor() ([]byte, []int) { + return file_controller_storage_credential_static_store_v1_static_proto_rawDescGZIP(), []int{2} +} + +func (x *UsernamePasswordDomainCredential) GetPublicId() string { + if x != nil { + return x.PublicId + } + return "" +} + +func (x *UsernamePasswordDomainCredential) GetCreateTime() *timestamp.Timestamp { + if x != nil { + return x.CreateTime + } + return nil +} + +func (x *UsernamePasswordDomainCredential) GetUpdateTime() *timestamp.Timestamp { + if x != nil { + return x.UpdateTime + } + return nil +} + +func (x *UsernamePasswordDomainCredential) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *UsernamePasswordDomainCredential) GetDescription() string { + if x != nil { + return x.Description + } + return "" +} + +func (x *UsernamePasswordDomainCredential) GetStoreId() string { + if x != nil { + return x.StoreId + } + return "" +} + +func (x *UsernamePasswordDomainCredential) GetVersion() uint32 { + if x != nil { + return x.Version + } + return 0 +} + +func (x *UsernamePasswordDomainCredential) GetUsername() string { + if x != nil { + return x.Username + } + return "" +} + +func (x *UsernamePasswordDomainCredential) GetPassword() []byte { + if x != nil { + return x.Password + } + return nil +} + +func (x *UsernamePasswordDomainCredential) GetCtPassword() []byte { + if x != nil { + return x.CtPassword + } + return nil +} + +func (x *UsernamePasswordDomainCredential) GetPasswordHmac() []byte { + if x != nil { + return x.PasswordHmac + } + return nil +} + +func (x *UsernamePasswordDomainCredential) GetKeyId() string { + if x != nil { + return x.KeyId + } + return "" +} + +func (x *UsernamePasswordDomainCredential) GetDomain() string { + if x != nil { + return x.Domain + } + return "" +} + type SshPrivateKeyCredential struct { state protoimpl.MessageState `protogen:"open.v1"` // public_id is a surrogate key suitable for use in a public API. @@ -361,7 +534,7 @@ type SshPrivateKeyCredential struct { func (x *SshPrivateKeyCredential) Reset() { *x = SshPrivateKeyCredential{} - mi := &file_controller_storage_credential_static_store_v1_static_proto_msgTypes[2] + mi := &file_controller_storage_credential_static_store_v1_static_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -373,7 +546,7 @@ func (x *SshPrivateKeyCredential) String() string { func (*SshPrivateKeyCredential) ProtoMessage() {} func (x *SshPrivateKeyCredential) ProtoReflect() protoreflect.Message { - mi := &file_controller_storage_credential_static_store_v1_static_proto_msgTypes[2] + mi := &file_controller_storage_credential_static_store_v1_static_proto_msgTypes[3] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -386,7 +559,7 @@ func (x *SshPrivateKeyCredential) ProtoReflect() protoreflect.Message { // Deprecated: Use SshPrivateKeyCredential.ProtoReflect.Descriptor instead. func (*SshPrivateKeyCredential) Descriptor() ([]byte, []int) { - return file_controller_storage_credential_static_store_v1_static_proto_rawDescGZIP(), []int{2} + return file_controller_storage_credential_static_store_v1_static_proto_rawDescGZIP(), []int{3} } func (x *SshPrivateKeyCredential) GetPublicId() string { @@ -540,7 +713,7 @@ type JsonCredential struct { func (x *JsonCredential) Reset() { *x = JsonCredential{} - mi := &file_controller_storage_credential_static_store_v1_static_proto_msgTypes[3] + mi := &file_controller_storage_credential_static_store_v1_static_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -552,7 +725,7 @@ func (x *JsonCredential) String() string { func (*JsonCredential) ProtoMessage() {} func (x *JsonCredential) ProtoReflect() protoreflect.Message { - mi := &file_controller_storage_credential_static_store_v1_static_proto_msgTypes[3] + mi := &file_controller_storage_credential_static_store_v1_static_proto_msgTypes[4] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -565,7 +738,7 @@ func (x *JsonCredential) ProtoReflect() protoreflect.Message { // Deprecated: Use JsonCredential.ProtoReflect.Descriptor instead. func (*JsonCredential) Descriptor() ([]byte, []int) { - return file_controller_storage_credential_static_store_v1_static_proto_rawDescGZIP(), []int{3} + return file_controller_storage_credential_static_store_v1_static_proto_rawDescGZIP(), []int{4} } func (x *JsonCredential) GetPublicId() string { @@ -684,7 +857,31 @@ const file_controller_storage_credential_static_store_v1_static_proto_rawDesc = "ctPassword\x12Q\n" + "\rpassword_hmac\x18\v \x01(\fB,\xc2\xdd)(\n" + "\fPasswordHmac\x12\x18attributes.password_hmacR\fpasswordHmac\x12\x15\n" + - "\x06key_id\x18\f \x01(\tR\x05keyId\"\xe7\a\n" + + "\x06key_id\x18\f \x01(\tR\x05keyId\"\xbc\x05\n" + + " UsernamePasswordDomainCredential\x12\x1b\n" + + "\tpublic_id\x18\x01 \x01(\tR\bpublicId\x12K\n" + + "\vcreate_time\x18\x02 \x01(\v2*.controller.storage.timestamp.v1.TimestampR\n" + + "createTime\x12K\n" + + "\vupdate_time\x18\x03 \x01(\v2*.controller.storage.timestamp.v1.TimestampR\n" + + "updateTime\x12$\n" + + "\x04name\x18\x04 \x01(\tB\x10\xc2\xdd)\f\n" + + "\x04Name\x12\x04nameR\x04name\x12@\n" + + "\vdescription\x18\x05 \x01(\tB\x1e\xc2\xdd)\x1a\n" + + "\vDescription\x12\vdescriptionR\vdescription\x12\x19\n" + + "\bstore_id\x18\x06 \x01(\tR\astoreId\x12\x18\n" + + "\aversion\x18\a \x01(\rR\aversion\x12?\n" + + "\busername\x18\b \x01(\tB#\xc2\xdd)\x1f\n" + + "\bUsername\x12\x13attributes.usernameR\busername\x12?\n" + + "\bpassword\x18\t \x01(\fB#\xc2\xdd)\x1f\n" + + "\bPassword\x12\x13attributes.passwordR\bpassword\x12\x1f\n" + + "\vct_password\x18\n" + + " \x01(\fR\n" + + "ctPassword\x12Q\n" + + "\rpassword_hmac\x18\v \x01(\fB,\xc2\xdd)(\n" + + "\fPasswordHmac\x12\x18attributes.password_hmacR\fpasswordHmac\x12\x15\n" + + "\x06key_id\x18\f \x01(\tR\x05keyId\x127\n" + + "\x06domain\x18\r \x01(\tB\x1f\xc2\xdd)\x1b\n" + + "\x06Domain\x12\x11attributes.domainR\x06domain\"\xe7\a\n" + "\x17SshPrivateKeyCredential\x12\x1b\n" + "\tpublic_id\x18\x01 \x01(\tR\bpublicId\x12K\n" + "\vcreate_time\x18\x02 \x01(\v2*.controller.storage.timestamp.v1.TimestampR\n" + @@ -747,28 +944,31 @@ func file_controller_storage_credential_static_store_v1_static_proto_rawDescGZIP return file_controller_storage_credential_static_store_v1_static_proto_rawDescData } -var file_controller_storage_credential_static_store_v1_static_proto_msgTypes = make([]protoimpl.MessageInfo, 4) +var file_controller_storage_credential_static_store_v1_static_proto_msgTypes = make([]protoimpl.MessageInfo, 5) var file_controller_storage_credential_static_store_v1_static_proto_goTypes = []any{ - (*CredentialStore)(nil), // 0: controller.storage.credential.static.store.v1.CredentialStore - (*UsernamePasswordCredential)(nil), // 1: controller.storage.credential.static.store.v1.UsernamePasswordCredential - (*SshPrivateKeyCredential)(nil), // 2: controller.storage.credential.static.store.v1.SshPrivateKeyCredential - (*JsonCredential)(nil), // 3: controller.storage.credential.static.store.v1.JsonCredential - (*timestamp.Timestamp)(nil), // 4: controller.storage.timestamp.v1.Timestamp + (*CredentialStore)(nil), // 0: controller.storage.credential.static.store.v1.CredentialStore + (*UsernamePasswordCredential)(nil), // 1: controller.storage.credential.static.store.v1.UsernamePasswordCredential + (*UsernamePasswordDomainCredential)(nil), // 2: controller.storage.credential.static.store.v1.UsernamePasswordDomainCredential + (*SshPrivateKeyCredential)(nil), // 3: controller.storage.credential.static.store.v1.SshPrivateKeyCredential + (*JsonCredential)(nil), // 4: controller.storage.credential.static.store.v1.JsonCredential + (*timestamp.Timestamp)(nil), // 5: controller.storage.timestamp.v1.Timestamp } var file_controller_storage_credential_static_store_v1_static_proto_depIdxs = []int32{ - 4, // 0: controller.storage.credential.static.store.v1.CredentialStore.create_time:type_name -> controller.storage.timestamp.v1.Timestamp - 4, // 1: controller.storage.credential.static.store.v1.CredentialStore.update_time:type_name -> controller.storage.timestamp.v1.Timestamp - 4, // 2: controller.storage.credential.static.store.v1.UsernamePasswordCredential.create_time:type_name -> controller.storage.timestamp.v1.Timestamp - 4, // 3: controller.storage.credential.static.store.v1.UsernamePasswordCredential.update_time:type_name -> controller.storage.timestamp.v1.Timestamp - 4, // 4: controller.storage.credential.static.store.v1.SshPrivateKeyCredential.create_time:type_name -> controller.storage.timestamp.v1.Timestamp - 4, // 5: controller.storage.credential.static.store.v1.SshPrivateKeyCredential.update_time:type_name -> controller.storage.timestamp.v1.Timestamp - 4, // 6: controller.storage.credential.static.store.v1.JsonCredential.create_time:type_name -> controller.storage.timestamp.v1.Timestamp - 4, // 7: controller.storage.credential.static.store.v1.JsonCredential.update_time:type_name -> controller.storage.timestamp.v1.Timestamp - 8, // [8:8] is the sub-list for method output_type - 8, // [8:8] is the sub-list for method input_type - 8, // [8:8] is the sub-list for extension type_name - 8, // [8:8] is the sub-list for extension extendee - 0, // [0:8] is the sub-list for field type_name + 5, // 0: controller.storage.credential.static.store.v1.CredentialStore.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 5, // 1: controller.storage.credential.static.store.v1.CredentialStore.update_time:type_name -> controller.storage.timestamp.v1.Timestamp + 5, // 2: controller.storage.credential.static.store.v1.UsernamePasswordCredential.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 5, // 3: controller.storage.credential.static.store.v1.UsernamePasswordCredential.update_time:type_name -> controller.storage.timestamp.v1.Timestamp + 5, // 4: controller.storage.credential.static.store.v1.UsernamePasswordDomainCredential.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 5, // 5: controller.storage.credential.static.store.v1.UsernamePasswordDomainCredential.update_time:type_name -> controller.storage.timestamp.v1.Timestamp + 5, // 6: controller.storage.credential.static.store.v1.SshPrivateKeyCredential.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 5, // 7: controller.storage.credential.static.store.v1.SshPrivateKeyCredential.update_time:type_name -> controller.storage.timestamp.v1.Timestamp + 5, // 8: controller.storage.credential.static.store.v1.JsonCredential.create_time:type_name -> controller.storage.timestamp.v1.Timestamp + 5, // 9: controller.storage.credential.static.store.v1.JsonCredential.update_time:type_name -> controller.storage.timestamp.v1.Timestamp + 10, // [10:10] is the sub-list for method output_type + 10, // [10:10] is the sub-list for method input_type + 10, // [10:10] is the sub-list for extension type_name + 10, // [10:10] is the sub-list for extension extendee + 0, // [0:10] is the sub-list for field type_name } func init() { file_controller_storage_credential_static_store_v1_static_proto_init() } @@ -782,7 +982,7 @@ func file_controller_storage_credential_static_store_v1_static_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_controller_storage_credential_static_store_v1_static_proto_rawDesc), len(file_controller_storage_credential_static_store_v1_static_proto_rawDesc)), NumEnums: 0, - NumMessages: 4, + NumMessages: 5, NumExtensions: 0, NumServices: 0, }, diff --git a/internal/credential/static/usernamepassworddomain_credential.go b/internal/credential/static/usernamepassworddomain_credential.go new file mode 100644 index 000000000..a16827530 --- /dev/null +++ b/internal/credential/static/usernamepassworddomain_credential.go @@ -0,0 +1,145 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +package static + +import ( + "context" + + "github.com/hashicorp/boundary/internal/credential" + "github.com/hashicorp/boundary/internal/credential/static/store" + "github.com/hashicorp/boundary/internal/db/timestamp" + "github.com/hashicorp/boundary/internal/errors" + "github.com/hashicorp/boundary/internal/libs/crypto" + "github.com/hashicorp/boundary/internal/oplog" + "github.com/hashicorp/boundary/internal/types/resource" + wrapping "github.com/hashicorp/go-kms-wrapping/v2" + "github.com/hashicorp/go-kms-wrapping/v2/extras/structwrapping" + "google.golang.org/protobuf/proto" +) + +var _ credential.Static = (*UsernamePasswordDomainCredential)(nil) + +// A UsernamePasswordDomainCredential contains the credential with a username, password, and domain. +// It is owned by a credential store. +type UsernamePasswordDomainCredential struct { + *store.UsernamePasswordDomainCredential + tableName string `gorm:"-"` +} + +// NewUsernamePasswordDomainCredential creates a new in memory static Credential containing a +// username, password, and domain that is assigned to storeId. Name and description are the only +// valid options. All other options are ignored. +func NewUsernamePasswordDomainCredential( + storeId string, + username string, + domain string, + password credential.Password, + opt ...Option, +) (*UsernamePasswordDomainCredential, error) { + opts := getOpts(opt...) + l := &UsernamePasswordDomainCredential{ + UsernamePasswordDomainCredential: &store.UsernamePasswordDomainCredential{ + StoreId: storeId, + Name: opts.withName, + Description: opts.withDescription, + Username: username, + Password: []byte(password), + Domain: domain, + }, + } + return l, nil +} + +func allocUsernamePasswordDomainCredential() *UsernamePasswordDomainCredential { + return &UsernamePasswordDomainCredential{ + UsernamePasswordDomainCredential: &store.UsernamePasswordDomainCredential{}, + } +} + +func (c *UsernamePasswordDomainCredential) clone() *UsernamePasswordDomainCredential { + cp := proto.Clone(c.UsernamePasswordDomainCredential) + return &UsernamePasswordDomainCredential{ + UsernamePasswordDomainCredential: cp.(*store.UsernamePasswordDomainCredential), + } +} + +// TableName returns the table name. +func (c *UsernamePasswordDomainCredential) TableName() string { + if c.tableName != "" { + return c.tableName + } + return "credential_static_username_password_domain_credential" +} + +// SetTableName sets the table name. +func (c *UsernamePasswordDomainCredential) SetTableName(n string) { + c.tableName = n +} + +// GetResourceType returns the resource type of the Credential +func (c *UsernamePasswordDomainCredential) GetResourceType() resource.Type { + return resource.Credential +} + +func (c *UsernamePasswordDomainCredential) oplog(op oplog.OpType) oplog.Metadata { + metadata := oplog.Metadata{ + "resource-public-id": []string{c.PublicId}, + "resource-type": []string{"credential-static-username-password-domain"}, + "op-type": []string{op.String()}, + } + if c.StoreId != "" { + metadata["store-id"] = []string{c.StoreId} + } + return metadata +} + +func (c *UsernamePasswordDomainCredential) encrypt(ctx context.Context, cipher wrapping.Wrapper) error { + const op = "static.(UsernamePasswordDomainCredential).encrypt" + if len(c.Password) == 0 { + return errors.New(ctx, errors.InvalidParameter, op, "no password defined") + } + if err := structwrapping.WrapStruct(ctx, cipher, c.UsernamePasswordDomainCredential, 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("error reading cipher key id")) + } + c.KeyId = keyId + if err := c.hmacPassword(ctx, cipher); err != nil { + return errors.Wrap(ctx, err, op) + } + return nil +} + +func (c *UsernamePasswordDomainCredential) decrypt(ctx context.Context, cipher wrapping.Wrapper) error { + const op = "static.(UsernamePasswordDomainCredential).decrypt" + if err := structwrapping.UnwrapStruct(ctx, cipher, c.UsernamePasswordDomainCredential, nil); err != nil { + return errors.Wrap(ctx, err, op, errors.WithCode(errors.Decrypt)) + } + return nil +} + +func (c *UsernamePasswordDomainCredential) hmacPassword(ctx context.Context, cipher wrapping.Wrapper) error { + const op = "static.(UsernamePasswordDomainCredential).hmacPassword" + if cipher == nil { + return errors.New(ctx, errors.InvalidParameter, op, "missing cipher") + } + hm, err := crypto.HmacSha256(ctx, c.Password, cipher, []byte(c.StoreId), nil, crypto.WithEd25519()) + if err != nil { + return errors.Wrap(ctx, err, op) + } + c.PasswordHmac = []byte(hm) + return nil +} + +type deletedUsernamePasswordDomainCredential struct { + PublicId string `gorm:"primary_key"` + DeleteTime *timestamp.Timestamp +} + +// TableName returns the tablename to override the default gorm table name +func (s *deletedUsernamePasswordDomainCredential) TableName() string { + return "credential_static_username_password_domain_credential_deleted" +} diff --git a/internal/credential/static/usernamepassworddomain_credential_test.go b/internal/credential/static/usernamepassworddomain_credential_test.go new file mode 100644 index 000000000..23c38980e --- /dev/null +++ b/internal/credential/static/usernamepassworddomain_credential_test.go @@ -0,0 +1,228 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +package static + +import ( + "context" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/hashicorp/boundary/internal/credential" + "github.com/hashicorp/boundary/internal/credential/static/store" + "github.com/hashicorp/boundary/internal/db" + "github.com/hashicorp/boundary/internal/iam" + "github.com/hashicorp/boundary/internal/kms" + "github.com/hashicorp/boundary/internal/libs/crypto" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/testing/protocmp" +) + +func TestUsernamePasswordDomainCredential_New(t *testing.T) { + t.Parallel() + conn, _ := db.TestSetup(t, "postgres") + wrapper := db.TestWrapper(t) + kkms := kms.TestKms(t, conn, wrapper) + rw := db.New(conn) + + _, prj := iam.TestScopes(t, iam.TestRepo(t, conn, wrapper)) + cs := TestCredentialStore(t, conn, wrapper, prj.PublicId) + + type args struct { + username string + password credential.Password + domain string + storeId string + options []Option + } + + tests := []struct { + name string + args args + want *UsernamePasswordDomainCredential + wantCreateErr bool + wantEncryptErr bool + }{ + { + name: "missing-password", + args: args{ + username: "test-user", + domain: "test-domain", + storeId: cs.PublicId, + }, + want: allocUsernamePasswordDomainCredential(), + wantEncryptErr: true, + }, + { + name: "missing-username", + args: args{ + password: "test-pass", + domain: "test-domain", + storeId: cs.PublicId, + }, + want: allocUsernamePasswordDomainCredential(), + wantCreateErr: true, + }, + { + name: "missing-domain", + args: args{ + username: "test-user", + password: "test-pass", + storeId: cs.PublicId, + }, + want: allocUsernamePasswordDomainCredential(), + wantCreateErr: true, + }, + { + name: "missing-password-domain", + args: args{ + username: "test-user", + storeId: cs.PublicId, + }, + want: allocUsernamePasswordDomainCredential(), + wantEncryptErr: true, + }, + + { + name: "missing-username-domain", + args: args{ + password: "test-pass", + storeId: cs.PublicId, + }, + want: allocUsernamePasswordDomainCredential(), + wantCreateErr: true, + }, + { + name: "missing-username-password", + args: args{ + domain: "test-domain", + storeId: cs.PublicId, + }, + want: allocUsernamePasswordDomainCredential(), + wantEncryptErr: true, + }, + { + name: "missing-store-id", + args: args{ + username: "test-user", + password: "test-pass", + domain: "test-domain", + }, + want: allocUsernamePasswordDomainCredential(), + wantCreateErr: true, + }, + { + name: "valid-no-options", + args: args{ + username: "test-user", + password: "test-pass", + domain: "test-domain", + storeId: cs.PublicId, + }, + want: &UsernamePasswordDomainCredential{ + UsernamePasswordDomainCredential: &store.UsernamePasswordDomainCredential{ + Username: "test-user", + Password: []byte("test-pass"), + Domain: "test-domain", + StoreId: cs.PublicId, + }, + }, + }, + { + name: "valid-with-name", + args: args{ + username: "test-user", + password: "test-pass", + domain: "test-domain", + storeId: cs.PublicId, + options: []Option{WithName("my-credential")}, + }, + want: &UsernamePasswordDomainCredential{ + UsernamePasswordDomainCredential: &store.UsernamePasswordDomainCredential{ + Username: "test-user", + Password: []byte("test-pass"), + Domain: "test-domain", + StoreId: cs.PublicId, + Name: "my-credential", + }, + }, + }, + { + name: "valid-with-description", + args: args{ + username: "test-user", + password: "test-pass", + domain: "test-domain", + storeId: cs.PublicId, + options: []Option{WithDescription("my-credential-description")}, + }, + want: &UsernamePasswordDomainCredential{ + UsernamePasswordDomainCredential: &store.UsernamePasswordDomainCredential{ + Username: "test-user", + Password: []byte("test-pass"), + Domain: "test-domain", + StoreId: cs.PublicId, + Description: "my-credential-description", + }, + }, + }, + } + for _, tt := range tests { + tt := tt + t.Run(tt.name, func(t *testing.T) { + assert, require := assert.New(t), require.New(t) + ctx := context.Background() + got, err := NewUsernamePasswordDomainCredential(tt.args.storeId, tt.args.username, tt.args.domain, tt.args.password, tt.args.options...) + require.NoError(err) + require.NotNil(got) + assert.Emptyf(got.PublicId, "PublicId set") + id, err := credential.NewUsernamePasswordDomainCredentialId(ctx) + require.NoError(err) + + tt.want.PublicId = id + got.PublicId = id + + databaseWrapper, err := kkms.GetWrapper(context.Background(), prj.PublicId, kms.KeyPurposeDatabase) + require.NoError(err) + + err = got.encrypt(ctx, databaseWrapper) + if tt.wantEncryptErr { + require.Error(err) + return + } + assert.NoError(err) + + err = rw.Create(context.Background(), got) + if tt.wantCreateErr { + require.Error(err) + return + } + assert.NoError(err) + + got2 := allocUsernamePasswordDomainCredential() + got2.PublicId = id + assert.Equal(id, got2.GetPublicId()) + require.NoError(rw.LookupById(ctx, got2)) + + err = got2.decrypt(ctx, databaseWrapper) + require.NoError(err) + + // Timestamps and version are automatically set + tt.want.CreateTime = got2.CreateTime + tt.want.UpdateTime = got2.UpdateTime + tt.want.Version = got2.Version + + // KeyId is allocated via kms no need to validate in this test + tt.want.KeyId = got2.KeyId + got2.CtPassword = nil + + // encrypt also calculates the hmac, validate it is correct + hm, err := crypto.HmacSha256(ctx, got.Password, databaseWrapper, []byte(got.StoreId), nil, crypto.WithEd25519()) + require.NoError(err) + tt.want.PasswordHmac = []byte(hm) + + assert.Empty(cmp.Diff(tt.want, got2.clone(), protocmp.Transform())) + }) + } +} diff --git a/internal/proto/controller/storage/credential/static/store/v1/static.proto b/internal/proto/controller/storage/credential/static/store/v1/static.proto index 24cba4fa0..0a2ea01ad 100644 --- a/internal/proto/controller/storage/credential/static/store/v1/static.proto +++ b/internal/proto/controller/storage/credential/static/store/v1/static.proto @@ -120,6 +120,85 @@ message UsernamePasswordCredential { string key_id = 12; } +message UsernamePasswordDomainCredential { + // public_id is a surrogate key suitable for use in a public API. + // @inject_tag: `gorm:"primary_key"` + string public_id = 1; + + // create_time is set by the database. + // @inject_tag: `gorm:"default:current_timestamp"` + timestamp.v1.Timestamp create_time = 2; + + // update_time is set by the database. + // @inject_tag: `gorm:"default:current_timestamp"` + timestamp.v1.Timestamp update_time = 3; + + // name is optional. If set, it must be unique within project_id. + // @inject_tag: `gorm:"default:null"` + string name = 4 [(custom_options.v1.mask_mapping) = { + this: "Name" + that: "name" + }]; + + // description is optional. + // @inject_tag: `gorm:"default:null"` + string description = 5 [(custom_options.v1.mask_mapping) = { + this: "Description" + that: "description" + }]; + + // store_id of the owning static credential store. + // It must be set. + // @inject_tag: `gorm:"not_null"` + string store_id = 6; + + // version allows optimistic locking of the resource. + // @inject_tag: `gorm:"default:null"` + uint32 version = 7; + + // username is the username associated with the credential. + // It must be set. + // @inject_tag: `gorm:"not_null"` + string username = 8 [(custom_options.v1.mask_mapping) = { + this: "Username" + that: "attributes.username" + }]; + + // password is the plain-text of the password associated with the credential. We are + // not storing this plain-text password in the database. + // @inject_tag: `gorm:"-" wrapping:"pt,password_data"` + bytes password = 9 [(custom_options.v1.mask_mapping) = { + this: "Password" + that: "attributes.password" + }]; + + // ct_password is the ciphertext of the password. It + // is stored in the database. + // @inject_tag: `gorm:"column:password_encrypted;not_null" wrapping:"ct,password_data"` + bytes ct_password = 10; + + // password_hmac is a sha256-hmac of the unencrypted password. It is recalculated + // everytime the password is updated. + // @inject_tag: `gorm:"not_null"` + bytes password_hmac = 11 [(custom_options.v1.mask_mapping) = { + this: "PasswordHmac" + that: "attributes.password_hmac" + }]; + + // The key_id of the kms database key used for encrypting this entry. + // It must be set. + // @inject_tag: `gorm:"not_null"` + string key_id = 12; + + // Domain is the domain associated with the credential.. + // It must be set. + // @inject_tag: `gorm:"not_null"` + string domain = 13 [(custom_options.v1.mask_mapping) = { + this: "Domain" + that: "attributes.domain" + }]; +} + message SshPrivateKeyCredential { // public_id is a surrogate key suitable for use in a public API. // @inject_tag: `gorm:"primary_key"`