Files
threshold/internal/credential/static/repository_credential.go
T
edd323b73a Key Rotation/Destruction (#2477) (#2607)
* Key Rotation/Destruction (#2477)

* fix: Correct kms.CreateKeys comment

This method does not return anything.

* feat(kms): Add new ListKeys method

The new ListKeys method wraps the underlying KMS wrapper,
returning all the keys in the scope specified.

* feat(scopes): Add new scope actions for key management

Adds list-keys, rotate-keys and revoke-keys actions for scopes.

* feat(scopes): Add ListKeys API endpoint

This new endpoint lists all keys in a scope

* feat(api): Add ListKeys to Scopes client

This has to be a custom function because it is a custom action
and doesn't map well to any of the existing templates, or
generalises well in a way that would make it reasonable
to create a new template.

* feat(cli): Add new scopes list-keys command

* add RotateKeys function to the kms repository

* Add Rotate Keys Endpoint to Scopes Api (#2360)

* add rotate keys endpoint

* add tests for RotateKeys endpoint

* remove that one comment I forgot about

* addressing more PR comments

* Add Rotate Keys CLI Command (#2395)

* add cli command and client

* add bats tests

* fix some info text and pr comments

* write a new rotate keys description

* Add Missing DEK Foreign Keys (#2408)

* add missing fks

* mark key as nullable in gorm

* update tests to use a new wrapper with a real key_id

* fix formatting in test and add keys for auth_token test

* replace key values

* revert postgres_40_01_test.go

* style: reformat sql for readability

* refactor: change type of key_id columns to kms_private_id

* Store key_id and scope_id with oplog entries, re-type columns referencing data key version (#2431)

* fix(db): Correct types of data key version referencers

* fix(oplog): Fix missing error handling

* feat(oplog): Store key_id and scope_id with oplog entries

This migration truncates all existing oplog entries, as
migrating existing data would have been complex and
likely unnecessary.

* Update view references

* Always delete oplog entries when dropping keys

* Fix rebase issues

* Fix sql tests

* Add schema for new kms destruction jobs (#2479)

* feat: Add schema for new kms destruction jobs

The schema lets us manage destruction jobs per-table
while providing a guarantee that only one run is running
at a time.

* Apply suggestions from code review

Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>

* Fix table reference and tests

Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>

* update domain, api, and cli to all include key versions in outputs (#2472)

* update domain, api, and cli to all include key versions in outputs

* fix go sum

* add migration to fix immutable error

* fix final test issue as well as make gen issue

* rebase and fix

* address johan pr comments

* make gen, didn't realize comments were included

* update migrations based on new migration 55 file 03

* Move migrations to 56

* feat: Add key version rewrapping function registry (#2478)

The new RegisterTableRewrapFn can be used by a domain
to register a callback to use when rewrapping data in a
specific table name.

* feat(kms): Add scopeId to RewrapFn (#2539)

This makes it much easier for rewrap functions to look up
the correct wrapper and limit the number of rows searched.

* Update Root Cert Proto Definition (#2542)

* update root cert proto definition to properly identify public_key as the table primary key

* add the test fix as well

* Rewrap Functions for Encrypted Tables (#2532)

* add oidc rewrap

* add argon2 config rewrap

* add auth token rewrapping

* add worker auth cert rewrapping

* check the err

* add username password credential rewrapping

* add ssh private key credential rewrapping

* add vault client certificate rewrap function

* add host catalog secret rewrap function

* cleanup a little

* add host vault token rewrap function

* add session credential rewrap function

* add session rewrap function

* add worker auth rewrap function

* update test to include full assert gamut

* add session rewrap function TEST

* bring all tests up to current standards, make more readable, and include full assert gamut

* rework all rewrap functions to utilize scope id

* update comments, queries, sql refs, etc, in response to PR comments

* forgot a comment

* remove hmac updates and fix a couple comments again

* Rewrapping Registered Tables Test (#2555)

* add the registered table test as well as the two missing rewrap functions

* address pr comments, add db r/w conversions, cmp.diff, sql comment, remove (now) faulty immutable test

* Add ability to list key version destruction jobs, recurring jobs and destroying key versions (#2498)

* feat(kms): Add ability to list data key version destruction jobs

* feat(scopes): Add ListKeyVersionDestructionJobs

* feat(cli): Add list-key-version-destruction-jobs

* feat(kms): Add recurring job that performs table rewrapping

The new recurring job runs for each job table with a registered
rewrapping callback. It attempts to become the running run and
start its rewrapping, gracefully handling sudden interruptions
by resuming it's work if it finds evidence of sudden interruption.

* feat(kms): Add recurring job for destroying key versions

The new job monitors the database for data key version destruction
jobs that have finished rewrapping all its data, performing
the final data key version revocation.

* feat(kms): Add DestroyKeyVersion

DestroyKeyVersion immediately destroys a key version
if it is a root key version or a data key version
which encrypts no data. If the data key version
encrypts data which needs to be rewrapped, it
queues an asynchronous job to complete the rewrapping
operation.

* feat(scopes): Add DestroyKeyVersion API endpoint

* feat(cli): Add scopes destroy-key-version CLI command

* Ensure all secret updates include key ID (#2556)

* feat(all): Ensure all secret updates include key ID

When updating a secret, it is paramount that the key ID
is also updated, as it is the only means we have of ensuring
that we only destroy keys once there is no more data
associated with the key.

* Remove fix to session repository for now

This breaks the current private key derivation method

* add new encrypt/decrypt funcs and made necessary proto changes (#2557)

* add new encrypt/decrypt funcs and made necessary proto changes

* address all PR comments

* fix test panic

* add param checking to rewraps

* fix(schema): Correctly organize migrations again

* Review comments part 1

* Review comments part 2

* Review comments part 3

* Store cert private key, encrypt tofu token (#2583)

* fix(session): store cert private key, encrypt tofu token

Previously, we would derive a session certificate private key from
the session key used in each project, and not store the key. We
would also encrypt the tofu token with the database key but not
store a reference to this key in the database.

This change fixes this by replacing our key derivation with a key
generation step, and instead store the generated key, encrypted,
in the database. We also ensure that any new tofu tokens are
encrypted with the same key.

To handle existing sessions, we lazily rewrite the sessions whenever
a user lists them. There is a minor risk that a user could end up
destroying the database key that encrypts the tofu token before
that session has been rewrapped, but this is going to be rare and
temporary.

* feat(session): Allow the random source for secrets to be configured

* Review comments

* Minor fixes

* More minor fixes

* More small fixes

Co-authored-by: Danielle Miu <dani.miu@hashicorp.com>
Co-authored-by: Danielle <29378233+DanielleMiu@users.noreply.github.com>
Co-authored-by: Michael Gaffney <mike@gaffney.cc>
Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>

* fix(session): Unset session key ID when scope is deleted

Unsetting the key ID allows the session to live beyond the lifetime of
the scope, while allowing the scope to cascade delete its keys.

* fix(migrations): Rewrite migration 56 tests

These tests can no longer use the normal test helpers
as they try to use the new oplog table structure, so we
have to manually write all the interactions.

* fix(migrations): Rename migration 58 file name

This was the name used in the release branch, update
it to the new migration number.

* fix(e2e): Add some comments and debug to kms tests

* fix(session): Handle empty project and user IDs in read

When a project or user is deleted, the session is automatically
canceled and the respective field on the session is unset.
LookupSession did not handle this case gracefully, and would
error on decryption in this state. Skip decrypting sessions that
do not have either a user or project to avoid this error. The
decrypted values are not used for a canceled session.

* Fix worker test

* Increase test timeout

Co-authored-by: Danielle Miu <dani.miu@hashicorp.com>
Co-authored-by: Danielle <29378233+DanielleMiu@users.noreply.github.com>
Co-authored-by: Michael Gaffney <mike@gaffney.cc>
Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>
2022-11-16 18:17:28 -05:00

839 lines
29 KiB
Go

package static
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/boundary/internal/credential"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/kms"
"github.com/hashicorp/boundary/internal/oplog"
"github.com/hashicorp/boundary/internal/types/subtypes"
"github.com/hashicorp/go-dbw"
)
// CreateUsernamePasswordCredential inserts c into the repository and returns a new
// UsernamePasswordCredential containing the credential's PublicId. c is not
// changed. c must not contain a PublicId. The PublicId is generated and
// assigned by this method. c must contain a valid StoreId.
//
// The password is encrypted and a HmacSha256 of the password is calculated. Only the
// PasswordHmac is returned, the plain-text and encrypted password is not returned.
//
// Both c.Name and c.Description are optional. If c.Name is set, it must
// be unique within c.ProjectId. Both c.CreateTime and c.UpdateTime are
// ignored.
func (r *Repository) CreateUsernamePasswordCredential(
ctx context.Context,
projectId string,
c *UsernamePasswordCredential,
_ ...Option,
) (*UsernamePasswordCredential, error) {
const op = "static.(Repository).CreateUsernamePasswordCredential"
if c == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing credential")
}
if c.UsernamePasswordCredential == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing embedded credential")
}
if projectId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing project id")
}
if c.Username == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing username")
}
if c.Password == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing password")
}
if c.StoreId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing store id")
}
if c.PublicId != "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "public id not empty")
}
c = c.clone()
id, err := credential.NewUsernamePasswordCredentialId(ctx)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
c.PublicId = id
oplogWrapper, err := r.kms.GetWrapper(ctx, projectId, kms.KeyPurposeOplog)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper"))
}
// encrypt
databaseWrapper, err := r.kms.GetWrapper(ctx, projectId, kms.KeyPurposeDatabase)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get database wrapper"))
}
if err := c.encrypt(ctx, databaseWrapper); err != nil {
return nil, errors.Wrap(ctx, err, op)
}
var newCred *UsernamePasswordCredential
_, err = r.writer.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{},
func(_ db.Reader, w db.Writer) error {
newCred = c.clone()
if err := w.Create(ctx, newCred,
db.WithOplog(oplogWrapper, newCred.oplog(oplog.OpType_OP_TYPE_CREATE))); err != nil {
return errors.Wrap(ctx, err, op)
}
return nil
},
)
if err != nil {
if errors.IsUniqueError(err) {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("in store: %s: name %s already exists", c.StoreId, c.Name)))
}
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("in store: %s", c.StoreId)))
}
// Clear password fields, only PasswordHmac should be returned
newCred.CtPassword = nil
newCred.Password = nil
return newCred, nil
}
// CreateSshPrivateKeyCredential inserts c into the repository and returns a new
// SshPrivateKeyCredential containing the credential's PublicId. c is not
// changed. c must not contain a PublicId. The PublicId is generated and
// assigned by this method. c must contain a valid StoreId.
//
// The private key is encrypted and a HmacSha256 of the private key is
// calculated. If a passphrase is supplied, it is also encrypted and an HmacSha256
// of passphrase is calculated. Only the PrivateKeyHmac (and
// PrivateKeyPassphraseHmac) is returned, the plain-text and encrypted private
// key and passphrase are not returned.
//
// Both c.Name and c.Description are optional. If c.Name is set, it must be
// unique within c.ProjectId. Both c.CreateTime and c.UpdateTime are ignored.
func (r *Repository) CreateSshPrivateKeyCredential(
ctx context.Context,
projectId string,
c *SshPrivateKeyCredential,
_ ...Option,
) (*SshPrivateKeyCredential, error) {
const op = "static.(Repository).CreateSshPrivateKeyCredential"
if c == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing credential")
}
if c.SshPrivateKeyCredential == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing embedded credential")
}
if projectId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing project id")
}
if c.Username == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing username")
}
if c.PrivateKey == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing private key")
}
if c.StoreId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing store id")
}
if c.PublicId != "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "public id not empty")
}
c = c.clone()
id, err := credential.NewSshPrivateKeyCredentialId(ctx)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
c.PublicId = id
oplogWrapper, err := r.kms.GetWrapper(ctx, projectId, kms.KeyPurposeOplog)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper"))
}
// encrypt
databaseWrapper, err := r.kms.GetWrapper(ctx, projectId, kms.KeyPurposeDatabase)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get database wrapper"))
}
if err := c.encrypt(ctx, databaseWrapper); err != nil {
return nil, errors.Wrap(ctx, err, op)
}
var newCred *SshPrivateKeyCredential
_, err = r.writer.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{},
func(_ db.Reader, w db.Writer) error {
newCred = c.clone()
if err := w.Create(ctx, newCred,
db.WithOplog(oplogWrapper, newCred.oplog(oplog.OpType_OP_TYPE_CREATE))); err != nil {
return errors.Wrap(ctx, err, op)
}
return nil
},
)
if err != nil {
if errors.IsUniqueError(err) {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("in store: %s: name %s already exists", c.StoreId, c.Name)))
}
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("in store: %s", c.StoreId)))
}
// Clear private key fields, only PrivateKeyHmac should be returned
newCred.PrivateKeyEncrypted = nil
newCred.PrivateKey = nil
// Clear passphrase fields, only PrivateKeyPassphraseHmac should be returned if it exists
newCred.PrivateKeyPassphraseEncrypted = nil
newCred.PrivateKeyPassphrase = nil
return newCred, nil
}
// CreateJsonCredential inserts c into the repository and returns a new
// JsonCredential containing the credential's PublicId. c is not
// changed. c must not contain a PublicId. The PublicId is generated and
// assigned by this method. c must contain a valid StoreId.
//
// The object is encrypted and a HmacSha256 of the object is
// calculated. Only the ObjectHmac is returned, the plain-text and encrypted
// object is not returned.
//
// Both c.Name and c.Description are optional. If c.Name is set, it must be
// unique within c.ProjectId. Both c.CreateTime and c.UpdateTime are ignored.
func (r *Repository) CreateJsonCredential(
ctx context.Context,
projectId string,
c *JsonCredential,
_ ...Option,
) (*JsonCredential, error) {
const op = "static.(Repository).CreateJsonCredential"
if c == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing credential")
}
if c.JsonCredential == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing embedded credential")
}
if projectId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing project id")
}
if c.Object == nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing object")
}
if c.StoreId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing store id")
}
if c.PublicId != "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "public id not empty")
}
c = c.clone()
id, err := credential.NewJsonCredentialId(ctx)
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
c.PublicId = id
oplogWrapper, err := r.kms.GetWrapper(ctx, projectId, kms.KeyPurposeOplog)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper"))
}
// encrypt
databaseWrapper, err := r.kms.GetWrapper(ctx, projectId, kms.KeyPurposeDatabase)
if err != nil {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get database wrapper"))
}
if err := c.encrypt(ctx, databaseWrapper); err != nil {
return nil, errors.Wrap(ctx, err, op)
}
var newCred *JsonCredential
_, err = r.writer.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{},
func(_ db.Reader, w db.Writer) error {
newCred = c.clone()
if err := w.Create(ctx, newCred,
db.WithOplog(oplogWrapper, newCred.oplog(oplog.OpType_OP_TYPE_CREATE))); err != nil {
return errors.Wrap(ctx, err, op)
}
return nil
},
)
if err != nil {
if errors.IsUniqueError(err) {
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("in store: %s: name %s already exists", c.StoreId, c.Name)))
}
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("in store: %s", c.StoreId)))
}
// Clear object fields, only ObjectHmac should be returned
newCred.ObjectEncrypted = nil
newCred.Object = nil
return newCred, nil
}
// LookupCredential returns the Credential for the publicId. Returns
// nil, nil if no Credential is found for the publicId.
// TODO: This should hit a view and return the interface type...
func (r *Repository) LookupCredential(ctx context.Context, publicId string, _ ...Option) (credential.Static, error) {
const op = "static.(Repository).LookupCredential"
if publicId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "no public id")
}
var cred credential.Static
switch subtypes.SubtypeFromId(credential.Domain, publicId) {
case credential.UsernamePasswordSubtype:
upCred := allocUsernamePasswordCredential()
upCred.PublicId = publicId
if err := r.reader.LookupByPublicId(ctx, upCred); err != nil {
if errors.IsNotFoundError(err) {
return nil, nil
}
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for: %s", publicId)))
}
// Clear password fields, only passwordHmac should be returned
upCred.CtPassword = nil
upCred.Password = nil
cred = upCred
case credential.SshPrivateKeySubtype:
spkCred := allocSshPrivateKeyCredential()
spkCred.PublicId = publicId
if err := r.reader.LookupByPublicId(ctx, spkCred); err != nil {
if errors.IsNotFoundError(err) {
return nil, nil
}
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for: %s", publicId)))
}
// Clear private key fields, only privateKeyHmac should be returned
spkCred.PrivateKeyEncrypted = nil
spkCred.PrivateKey = nil
// Clear passphrase fields, only PrivateKeyPassphraseHmac should be returned if it exists
spkCred.PrivateKeyPassphraseEncrypted = nil
spkCred.PrivateKeyPassphrase = nil
cred = spkCred
case credential.JsonSubtype:
jsonCred := allocJsonCredential()
jsonCred.PublicId = publicId
if err := r.reader.LookupByPublicId(ctx, jsonCred); err != nil {
if errors.IsNotFoundError(err) {
return nil, nil
}
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for : %s", publicId)))
}
// Clear object fields, only ObjectHmac should be returned
jsonCred.ObjectEncrypted = nil
jsonCred.Object = nil
cred = jsonCred
}
return cred, nil
}
// UpdateUsernamePasswordCredential updates the repository entry for c.PublicId with
// the values in c for the fields listed in fieldMaskPaths. It returns a
// new UsernamePasswordCredential containing the updated values and a count of the
// number of records updated. c is not changed.
//
// c must contain a valid PublicId. Only Name, Description, Username and Password can be
// changed. If c.Name is set to a non-empty string, it must be unique within c.ProjectId.
//
// An attribute of c will be set to NULL in the database if the attribute
// in c is the zero value and it is included in fieldMaskPaths.
func (r *Repository) UpdateUsernamePasswordCredential(ctx context.Context,
projectId string,
c *UsernamePasswordCredential,
version uint32,
fieldMaskPaths []string,
_ ...Option,
) (*UsernamePasswordCredential, int, error) {
const op = "static.(Repository).UpdateUsernamePasswordCredential"
if c == nil {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing credential")
}
if c.UsernamePasswordCredential == nil {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing embedded credential")
}
if c.PublicId == "" {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidPublicId, op, "missing public id")
}
if version == 0 {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing version")
}
if projectId == "" {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing project id")
}
if c.StoreId == "" {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing store id")
}
c = c.clone()
for _, f := range fieldMaskPaths {
switch {
case strings.EqualFold(nameField, f):
case strings.EqualFold(descriptionField, f):
case strings.EqualFold(usernameField, f):
case strings.EqualFold(passwordField, f):
default:
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidFieldMask, op, f)
}
}
dbMask, nullFields := dbw.BuildUpdatePaths(
map[string]any{
nameField: c.Name,
descriptionField: c.Description,
usernameField: c.Username,
passwordField: c.Password,
},
fieldMaskPaths,
nil,
)
if len(dbMask) == 0 && len(nullFields) == 0 {
return nil, db.NoRowsAffected, errors.New(ctx, errors.EmptyFieldMask, op, "missing field mask")
}
for _, f := range fieldMaskPaths {
if strings.EqualFold(passwordField, f) {
// Password has been updated, re-encrypt and recalculate hmac
databaseWrapper, err := r.kms.GetWrapper(ctx, projectId, kms.KeyPurposeDatabase)
if err != nil {
return nil, db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get database wrapper"))
}
if err := c.encrypt(ctx, databaseWrapper); err != nil {
return nil, db.NoRowsAffected, errors.Wrap(ctx, err, op)
}
// Set PasswordHmac and CtPassword masks for update.
dbMask = append(dbMask, "PasswordHmac", "CtPassword", "KeyId")
}
}
oplogWrapper, err := r.kms.GetWrapper(ctx, projectId, kms.KeyPurposeOplog)
if err != nil {
return nil, db.NoRowsAffected,
errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper"))
}
var rowsUpdated int
var returnedCredential *UsernamePasswordCredential
_, err = r.writer.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{},
func(_ db.Reader, w db.Writer) error {
returnedCredential = c.clone()
var err error
rowsUpdated, err = w.Update(ctx, returnedCredential,
dbMask, nullFields,
db.WithOplog(oplogWrapper, returnedCredential.oplog(oplog.OpType_OP_TYPE_UPDATE)),
db.WithVersion(&version))
if err != nil {
return errors.Wrap(ctx, err, op)
}
if rowsUpdated > 1 {
return errors.New(ctx, errors.MultipleRecords, op, "more than 1 resource would have been updated")
}
return nil
},
)
if err != nil {
return nil, db.NoRowsAffected, err
}
// Clear password fields, only PasswordHmac should be returned
returnedCredential.CtPassword = nil
returnedCredential.Password = nil
return returnedCredential, rowsUpdated, nil
}
// UpdateSshPrivateKeyCredential updates the repository entry for c.PublicId
// with the values in c for the fields listed in fieldMaskPaths. It returns a
// new SshPrivateKeyCredential containing the updated values and a count of the
// number of records updated. c is not changed.
//
// c must contain a valid PublicId. Only Name, Description, Username,
// PrivateKey and PrivateKeyPassphrase can be changed. If c.Name is set to a non-empty string, it
// must be unique within c.ProjectId.
//
// An attribute of c will be set to NULL in the database if the attribute in c
// is the zero value and it is included in fieldMaskPaths.
func (r *Repository) UpdateSshPrivateKeyCredential(ctx context.Context,
projectId string,
c *SshPrivateKeyCredential,
version uint32,
fieldMaskPaths []string,
_ ...Option,
) (*SshPrivateKeyCredential, int, error) {
const op = "static.(Repository).UpdateSshPrivateKeyCredential"
if c == nil {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing credential")
}
if c.SshPrivateKeyCredential == nil {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing embedded credential")
}
if c.PublicId == "" {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidPublicId, op, "missing public id")
}
if version == 0 {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing version")
}
if projectId == "" {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing project id")
}
if c.StoreId == "" {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing store id")
}
c = c.clone()
for _, f := range fieldMaskPaths {
switch {
case strings.EqualFold(nameField, f):
case strings.EqualFold(descriptionField, f):
case strings.EqualFold(usernameField, f):
case strings.EqualFold(privateKeyField, f):
case strings.EqualFold(PrivateKeyPassphraseField, f):
default:
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidFieldMask, op, f)
}
}
dbMask, nullFields := dbw.BuildUpdatePaths(
map[string]any{
nameField: c.Name,
descriptionField: c.Description,
usernameField: c.Username,
privateKeyField: c.PrivateKey,
PrivateKeyPassphraseField: c.PrivateKeyPassphrase,
},
fieldMaskPaths,
nil,
)
if len(dbMask) == 0 && len(nullFields) == 0 {
return nil, db.NoRowsAffected, errors.New(ctx, errors.EmptyFieldMask, op, "missing field mask")
}
var performedEncryption bool
for _, f := range fieldMaskPaths {
if strings.EqualFold(privateKeyField, f) || strings.EqualFold(PrivateKeyPassphraseField, f) {
if !performedEncryption {
// We don't need to encrypt twice so keep track
performedEncryption = true
databaseWrapper, err := r.kms.GetWrapper(ctx, projectId, kms.KeyPurposeDatabase)
if err != nil {
return nil, db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get database wrapper"))
}
if err := c.encrypt(ctx, databaseWrapper); err != nil {
return nil, db.NoRowsAffected, errors.Wrap(ctx, err, op)
}
}
dbMask = append(dbMask, "KeyId")
if strings.EqualFold(privateKeyField, f) {
// Set PrivateKeyHmac and PrivateKeyEncrypted masks for update.
dbMask = append(dbMask, "PrivateKeyHmac", "PrivateKeyEncrypted")
}
if strings.EqualFold(PrivateKeyPassphraseField, f) {
// Set PassphraseHmac and PassphraseEncrypted masks for update.
dbMask = append(dbMask, "PrivateKeyPassphraseHmac", "PrivateKeyPassphraseEncrypted")
}
}
}
oplogWrapper, err := r.kms.GetWrapper(ctx, projectId, kms.KeyPurposeOplog)
if err != nil {
return nil, db.NoRowsAffected,
errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper"))
}
var rowsUpdated int
var returnedCredential *SshPrivateKeyCredential
_, err = r.writer.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{},
func(_ db.Reader, w db.Writer) error {
returnedCredential = c.clone()
var err error
rowsUpdated, err = w.Update(ctx, returnedCredential,
dbMask, nullFields,
db.WithOplog(oplogWrapper, returnedCredential.oplog(oplog.OpType_OP_TYPE_UPDATE)),
db.WithVersion(&version))
if err != nil {
return errors.Wrap(ctx, err, op)
}
if rowsUpdated > 1 {
return errors.New(ctx, errors.MultipleRecords, op, "more than 1 resource would have been updated")
}
return nil
},
)
if err != nil {
return nil, db.NoRowsAffected, err
}
// Clear private key fields, only PrivateKeyHmac should be returned
returnedCredential.PrivateKeyEncrypted = nil
returnedCredential.PrivateKey = nil
// Clear passphrase fields, only PrivateKeyPassphraseHmac should be returned if it exists
returnedCredential.PrivateKeyPassphraseEncrypted = nil
returnedCredential.PrivateKeyPassphrase = nil
return returnedCredential, rowsUpdated, nil
}
// UpdateJsonCredential updates the repository entry for c.PublicId
// with the values in c for the fields listed in fieldMaskPaths. It returns a
// new JsonCredential containing the updated values and a count of the
// number of records updated. c is not changed.
//
// c must contain a valid PublicId. Only Name, Description and
// Json can be changed. If c.Name is set to a non-empty string, it must be
// unique within c.ProjectId.
//
// An attribute of c will be set to NULL in the database if the attribute in c
// is the zero value and it is included in fieldMaskPaths.
func (r *Repository) UpdateJsonCredential(ctx context.Context,
projectId string,
c *JsonCredential,
version uint32,
fieldMaskPaths []string,
_ ...Option,
) (*JsonCredential, int, error) {
const op = "static.(Repository).UpdateJsonCredential"
if c == nil {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing credential")
}
if c.JsonCredential == nil {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing embedded credential")
}
if c.PublicId == "" {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidPublicId, op, "missing public id")
}
if version == 0 {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing version")
}
if projectId == "" {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing project id")
}
if c.StoreId == "" {
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing store id")
}
c = c.clone()
// each field in the json secret will be passed into the fieldMaskPaths as an individual path
// that shares the same prefix: attributes.object.
// for example attributes.object.username & attributes.object.password
// fieldMaskPaths elements will be deduped if sharing the same prefix attributes.object.
// and the values will be substituted with a single value Object.
var hasSecret bool
reducedFieldMaskPaths := []string{}
for _, f := range fieldMaskPaths {
if strings.HasPrefix(f, "attributes.object.") {
hasSecret = true
continue
}
reducedFieldMaskPaths = append(reducedFieldMaskPaths, f)
}
if hasSecret {
reducedFieldMaskPaths = append(reducedFieldMaskPaths, objectField)
}
for _, f := range reducedFieldMaskPaths {
switch {
case strings.EqualFold(nameField, f):
case strings.EqualFold(descriptionField, f):
case strings.EqualFold(objectField, f):
default:
return nil, db.NoRowsAffected, errors.New(ctx, errors.InvalidFieldMask, op, f)
}
}
dbMask, nullFields := dbw.BuildUpdatePaths(
map[string]any{
nameField: c.Name,
descriptionField: c.Description,
objectField: c.Object,
},
reducedFieldMaskPaths,
nil,
)
if len(dbMask) == 0 && len(nullFields) == 0 {
return nil, db.NoRowsAffected, errors.New(ctx, errors.EmptyFieldMask, op, "missing field mask")
}
if hasSecret {
// Json secret has been updated, re-encrypt and recalculate hmac
databaseWrapper, err := r.kms.GetWrapper(ctx, projectId, kms.KeyPurposeDatabase)
if err != nil {
return nil, db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get database wrapper"))
}
if err := c.encrypt(ctx, databaseWrapper); err != nil {
return nil, db.NoRowsAffected, errors.Wrap(ctx, err, op)
}
// Set ObjectHmac and ObjectEncrypted masks for update.
dbMask = append(dbMask, "ObjectHmac", "ObjectEncrypted", "KeyId")
}
oplogWrapper, err := r.kms.GetWrapper(ctx, projectId, kms.KeyPurposeOplog)
if err != nil {
return nil, db.NoRowsAffected,
errors.Wrap(ctx, err, op, errors.WithMsg("unable to get oplog wrapper"))
}
var rowsUpdated int
var returnedCredential *JsonCredential
_, err = r.writer.DoTx(ctx, db.StdRetryCnt, db.ExpBackoff{},
func(_ db.Reader, w db.Writer) error {
returnedCredential = c.clone()
var err error
rowsUpdated, err = w.Update(ctx, returnedCredential,
dbMask, nullFields,
db.WithOplog(oplogWrapper, returnedCredential.oplog(oplog.OpType_OP_TYPE_UPDATE)),
db.WithVersion(&version))
if err != nil {
return errors.Wrap(ctx, err, op)
}
if rowsUpdated > 1 {
return errors.New(ctx, errors.MultipleRecords, op, "more than 1 resource would have been updated")
}
return nil
},
)
if err != nil {
return nil, db.NoRowsAffected, err
}
// Clear object fields, only ObjectHmac should be returned
returnedCredential.ObjectEncrypted = nil
returnedCredential.Object = nil
return returnedCredential, rowsUpdated, nil
}
// ListCredentials returns a slice of UsernamePasswordCredentials, SshPrivateKeyCredentials, and JsonCredentials
// for the storeId. WithLimit is the only option supported.
// TODO: This should hit a view and return the interface type...
func (r *Repository) ListCredentials(ctx context.Context, storeId string, opt ...Option) ([]credential.Static, error) {
const op = "static.(Repository).ListCredentials"
if storeId == "" {
return nil, errors.New(ctx, errors.InvalidParameter, op, "no storeId")
}
opts := getOpts(opt...)
limit := r.defaultLimit
if opts.withLimit != 0 {
// non-zero signals an override of the default limit for the repo.
limit = opts.withLimit
}
var upCreds []*UsernamePasswordCredential
err := r.reader.SearchWhere(ctx, &upCreds, "store_id = ?", []any{storeId}, db.WithLimit(limit))
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
var spkCreds []*SshPrivateKeyCredential
err = r.reader.SearchWhere(ctx, &spkCreds, "store_id = ?", []any{storeId}, db.WithLimit(limit))
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
var jsonCreds []*JsonCredential
err = r.reader.SearchWhere(ctx, &jsonCreds, "store_id = ?", []any{storeId}, db.WithLimit(limit))
if err != nil {
return nil, errors.Wrap(ctx, err, op)
}
ret := make([]credential.Static, 0, len(upCreds)+len(spkCreds)+len(jsonCreds))
for _, c := range upCreds {
// Clear password fields, only PasswordHmac should be returned
c.CtPassword = nil
c.Password = nil
ret = append(ret, c)
}
for _, c := range spkCreds {
// Clear private key fields, only PrivateKeyHmac should be returned
c.PrivateKeyEncrypted = nil
c.PrivateKey = nil
// Clear passphrase fields, only PrivateKeyPassphraseHmac should be returned if it exists
c.PrivateKeyPassphraseEncrypted = nil
c.PrivateKeyPassphrase = nil
ret = append(ret, c)
}
for _, c := range jsonCreds {
// Clear the object fields, only ObjectHmac should be returned
c.ObjectEncrypted = nil
c.Object = nil
ret = append(ret, c)
}
return ret, nil
}
// DeleteCredential deletes publicId from the repository and returns
// the number of records deleted. All options are ignored.
// TODO: This should hit a view...
func (r *Repository) DeleteCredential(ctx context.Context, projectId, id string, _ ...Option) (int, error) {
const op = "static.(Repository).DeleteCredential"
if id == "" {
return db.NoRowsAffected, errors.New(ctx, errors.InvalidPublicId, op, "missing public id")
}
if projectId == "" {
return db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "no project id")
}
var input any
var md oplog.Metadata
switch subtypes.SubtypeFromId(credential.Domain, id) {
case credential.UsernamePasswordSubtype:
c := allocUsernamePasswordCredential()
c.PublicId = id
input = c
md = c.oplog(oplog.OpType_OP_TYPE_DELETE)
case credential.SshPrivateKeySubtype:
c := allocSshPrivateKeyCredential()
c.PublicId = id
input = c
md = c.oplog(oplog.OpType_OP_TYPE_DELETE)
case credential.JsonSubtype:
c := allocJsonCredential()
c.PublicId = id
input = c
md = c.oplog(oplog.OpType_OP_TYPE_DELETE)
default:
return db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "unknown type")
}
oplogWrapper, err := r.kms.GetWrapper(ctx, projectId, kms.KeyPurposeOplog)
if err != nil {
return db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithCode(errors.Encrypt), errors.WithMsg("unable to get oplog wrapper"))
}
var rowsDeleted int
_, err = r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(_ db.Reader, w db.Writer) (err error) {
rowsDeleted, err = w.Delete(ctx, input, db.WithOplog(oplogWrapper, md))
if err != nil {
return errors.Wrap(ctx, err, op)
}
if rowsDeleted > 1 {
return errors.New(ctx, errors.MultipleRecords, op, "more than 1 resource would have been deleted")
}
return nil
},
)
if err != nil {
return db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg(id))
}
return rowsDeleted, nil
}