Files
threshold/internal/target/repository_host_set.go
T
df35699c4e Integrate with Vault to retrieve and manage per session credentials (#1308)
* Fix down migrations

* Udpates due to merge

* Sentinel values only have to be greater than 0

* Create credential related sdk structs and methods.

* Post merge interface updating.

* Removing scratch code that was not cleaned up.

* updates

* Convert client certificate and client certificate keys into pem blocks and validate.

* Add newline at end of file.

* Faster check for "s" at the end of a resource name when generating from templates.

* make fmt

* updates

* Add dynamic credentials to a session

* Refactor: move contents of file

* updates

* Updates

* Add InvalidDynamicCredential error

* Assign credentials

* Allow updating client certificates seperate from the client certificate key.

* Replace application purpose string with enum value

* PR feedback / fix go test .

* Delete dead code

* Use common view

* Refactor: extract interface and rename method

* Refactor: move code to eliminate privPurpLibrary

* Add comment to requestMap

* Refactor: do not export methods on an unexported struct

* Update internal/db/schema/migrations/postgres/10/03_vault_credential.up.sql

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

* Add comments to credential Purpose constants

* Reorder switch statements to handle errors first

* PR feedback

* update

* fix merge

* Organizing the scheduler code and extract the individual store creation test helper function.

* Run 'make fmt'

* Create certificate when creating store.  Allow vault address to be passed in as option

* Refactor: rename database views and associated structs

This change renames two database views and associated go structs to use
a consistent naming pattern. Views ending in 'private' contain encrypted
credentials needed for connecting to Vault. Views ending in 'public'
mirror the 'private' views but do not include any encrypted values.

This change does not include any changes to functionality or behavior.

* Adding SAD target operations for credential libraries to the SDK.

* Add status field and enumeration table for credential status

* Refactor: rename Status to TokenStatus

* Add status to vault credentials

* Creating the template for the CLI and helper functions.

* Add private database view for vault credentials

* Add scope_id to view and cleanup TODO comment

* Reformat embedded sql queries

* Add vault client helpers

* updates

* white space

* Add LookupLease test

* CLI commands for Store work.  Renamed fields in proto w/ vault prefix.

* Test issue credentials with client TLS

* Add additional checks to vault ping

* Add an error for vault token capabilities and create a VaultToken error kind

* Add support for working with Vault policies

* Use Vault 1.7.2 for testing

* Add testing helper for creating a vault client with a non-root token

* Fix Vault renew lease test

The Vault renew lease endpoint accepts an optional duration parameter
for requesting the number of seconds to extend the lease by. However,
Vault is not required to honor this request.

* Add a var for the required capabilities of a boundary Vault token

* Enhance the test helper for adding a policy to Vault

* Allow the test role in postgresql to revoke credentials

* Remove out of date comments

* Enhance Vault test helpers for the database secrets engine

* Reformat comments

* Add a method for getting the capabilities of the current Vault token

* Add revoke lease to internal Vault client

* Reformat: combine err return line with check for nil line

* Remove redundant checks in test code

Remove checks in test code that are redundant with checks in the test
harness.

* Refactor CreateToken test helper to return the secret and the token

* Fix build failures caused by signature change in vault.CreateToken

* Fix Vault version and Vault API link in comments

* ran `make gen` after merging from mgaffney-vault.

* Remove Vault prefix from attribute fields in API, create a base CLI option for adding field prefixes. format now uses that prefix for error reporting.

* Template now allows attaching attribute field prefixes.

* Credential store uses PrefixAttributeFieldErrorsWithSubactionPrefix.

* Fixing naming of vault flags and helper flags.

* Updating more references to generated api methods.

* Make the capabilities String method more readable

* Add comment outlining PrintApiError usage of Options.

* Refactor test to move declarations closer to first use

* Fix comment

* Implement revoke method on vault repository

* Tests now verify certs, CA, and tokens, addresses can be updated in a store.

* Added test for creating store with pk/cert in same field.

* Allo updating certificates seperate from private key.  Only contact backing vault service when updating token.

* Fixing bad tests and removing unused code.

* Adding tests for various ways of updating tokens.

* Add private credential

* Add token revocation job and cred renewal/revocation job

* Regen after merge.

* Fixing field mask related merge error.

* Create Library CLI. Removes vault prefix from path. Adds a WithoutCleanup testOption for vault.

* Set all credentials to revoked when a token is revoked

* Fixing missed renaming update.

* fix copy/paste error.

* Fixing code generation errors after merge.

* make gen after merge.

* Update internal/cmd/commands/credentialstorescmd/vault_funcs.go

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

* Update internal/cmd/commands/credentialstorescmd/vault_funcs.go

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

* Update internal/cmd/commands/credentialstorescmd/vault_funcs.go

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

* Refactor: move migrations from 10 to 12

* Removing logic from transaction.

* wrapping client errors in the calling op for CredentialStore's client() method.

* Redact token

* redact client key

* updates

* Add trigger to revoke credentials when session is canceled or terminated

* Fixing some help text for some flags.

* Add ability to load values from files (file://) or environment variables (env://).

* Updating comments

* fix bad merge

* feedback

* Adding issued credentials to sessions.

* Error on capabilities

* updates

* Expose NewVaulTestServer

* Add godoc

* Adding generated SessionCredential struct for API.

* Progress on building handler test for Authorize Session.

* feedback

* Update policies

* Add 'revoke' as a status for Vault Tokens

* Add delete_time to vault credential store

* Create dynamic credentials at session creation time.

* Tests pass with credentials attached to AuthorizedSession result.

* Only call issue if there are credentials to issue.

* Fixing output only issues. Adding type to credential library.

* Fix test to clear un/pw generated.  confirm generated un/pw changes from 1 authorize session call to another.

* Update lookupTokenError

* Add delete_time to private credential store

* Refactor: move private store to separate file

* Fixing tests for AuthorizeSession and verifying error cases.

* Only create the credential repo if there are credentials to issue.

* Rename Library field to CredentialLibrary.

* Fixing missing change of Library to CredentialLibrary.

* Removing Default SDK functions for fields which are required and update CLI to match.

* Replace resource specific id variables with "id" and the input parmater for paths to be just a single string and the resource name as it should show up in the path.

* Soft delete vault credential stores

* Prevent new SQL functions from silently overwriting existing functions

* Rename "Hmac" to "HMAC" in the human readable cli response table.

* Fix tests

* Add vault database cleanup jobs

* Add ability to set the token period in the vault test harness

* updates

* Add not_null_columns func test

* remove unused struct

* Up no output timeout

* Validate current vault token on addr update

* Fix client cert change test

* add cert test

* Update revocation job where

* Fix comment

* Use Vault's default port in CLI help strings

* Remove down migrations

* Increase migration file numbers by 1

* Run make migrations

* Move migrations from 12 to 10

* Increase Circle CI timeout for acceptance tests

* Fix spelling mistake in error messages

* ASD cmds for Target and returning credentials to AuthSession request (#1338)

* Add Add/Set/Remove commands for libraries on Targets.  Return credentials on AuthorizeSession request.

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

Co-authored-by: Louis Ruch <louisruch@gmail.com>
Co-authored-by: Todd Knight <T.Alan.Knight@gmail.com>
Co-authored-by: Jeff Mitchell <jeffrey.mitchell@gmail.com>
2021-06-22 22:26:26 -04:00

361 lines
14 KiB
Go

package target
import (
"context"
"fmt"
"github.com/hashicorp/boundary/internal/db"
"github.com/hashicorp/boundary/internal/errors"
"github.com/hashicorp/boundary/internal/kms"
"github.com/hashicorp/boundary/internal/oplog"
)
// AddTargetHostSets provides the ability to add host sets (hostSetIds) to a
// target (targetId). The target's current db version must match the
// targetVersion or an error will be returned. The target and a list of
// current host set ids will be returned on success. Zero is not a valid value
// for the WithVersion option and will return an error.
func (r *Repository) AddTargetHostSets(ctx context.Context, targetId string, targetVersion uint32, hostSetIds []string, _ ...Option) (Target, []*TargetSet, []*TargetLibrary, error) {
const op = "target.(Repository).AddTargetHostSets"
if targetId == "" {
return nil, nil, nil, errors.New(errors.InvalidParameter, op, "missing target id")
}
if targetVersion == 0 {
return nil, nil, nil, errors.New(errors.InvalidParameter, op, "missing version")
}
if len(hostSetIds) == 0 {
return nil, nil, nil, errors.New(errors.InvalidParameter, op, "missing host set ids")
}
newHostSets := make([]interface{}, 0, len(hostSetIds))
for _, id := range hostSetIds {
ths, err := NewTargetHostSet(targetId, id)
if err != nil {
return nil, nil, nil, errors.Wrap(err, op, errors.WithMsg("unable to create in memory target host set"))
}
newHostSets = append(newHostSets, ths)
}
t := allocTargetView()
t.PublicId = targetId
if err := r.reader.LookupByPublicId(ctx, &t); err != nil {
return nil, nil, nil, errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("failed for %s", targetId)))
}
var metadata oplog.Metadata
var target interface{}
switch t.Type {
case TcpTargetType.String():
tcpT := allocTcpTarget()
tcpT.PublicId = t.PublicId
tcpT.Version = targetVersion + 1
target = &tcpT
metadata = tcpT.oplog(oplog.OpType_OP_TYPE_UPDATE)
metadata["op-type"] = append(metadata["op-type"], oplog.OpType_OP_TYPE_CREATE.String())
default:
return nil, nil, nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("%s is an unsupported target type %s", t.PublicId, t.Type))
}
oplogWrapper, err := r.kms.GetWrapper(ctx, t.GetScopeId(), kms.KeyPurposeOplog)
if err != nil {
return nil, nil, nil, errors.Wrap(err, op, errors.WithMsg("unable to get oplog wrapper"))
}
var currentHostSets []*TargetSet
var currentCredLibs []*TargetLibrary
var updatedTarget interface{}
_, err = r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(reader db.Reader, w db.Writer) error {
msgs := make([]*oplog.Message, 0, 2)
targetTicket, err := w.GetTicket(target)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to get ticket"))
}
updatedTarget = target.(Cloneable).Clone()
var targetOplogMsg oplog.Message
rowsUpdated, err := w.Update(ctx, updatedTarget, []string{"Version"}, nil, db.NewOplogMsg(&targetOplogMsg), db.WithVersion(&targetVersion))
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to update target version"))
}
if rowsUpdated != 1 {
return errors.New(errors.MultipleRecords, op, fmt.Sprintf("updated target and %d rows updated", rowsUpdated))
}
msgs = append(msgs, &targetOplogMsg)
hostSetsOplogMsgs := make([]*oplog.Message, 0, len(newHostSets))
if err := w.CreateItems(ctx, newHostSets, db.NewOplogMsgs(&hostSetsOplogMsgs)); err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to add target host sets"))
}
msgs = append(msgs, hostSetsOplogMsgs...)
if err := w.WriteOplogEntryWith(ctx, oplogWrapper, targetTicket, metadata, msgs); err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to write oplog"))
}
currentHostSets, err = fetchSets(ctx, reader, targetId)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to retrieve current host sets after adds"))
}
currentCredLibs, err = fetchLibraries(ctx, reader, targetId)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to retrieve current credential libraries after adds"))
}
return nil
},
)
if err != nil {
return nil, nil, nil, errors.Wrap(err, op, errors.WithMsg("error creating sets"))
}
return updatedTarget.(Target), currentHostSets, currentCredLibs, nil
}
// DeleteTargeHostSets deletes host sets from a target (targetId). The target's
// current db version must match the targetVersion or an error will be returned.
// Zero is not a valid value for the WithVersion option and will return an
// error.
func (r *Repository) DeleteTargeHostSets(ctx context.Context, targetId string, targetVersion uint32, hostSetIds []string, _ ...Option) (int, error) {
const op = "target.(Repository).DeleteTargeHostSets"
if targetId == "" {
return db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing target id")
}
if targetVersion == 0 {
return db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing version")
}
if len(hostSetIds) == 0 {
return db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing host set ids")
}
deleteTargeHostSets := make([]interface{}, 0, len(hostSetIds))
for _, id := range hostSetIds {
ths, err := NewTargetHostSet(targetId, id)
if err != nil {
return db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("unable to create in memory target host set"))
}
deleteTargeHostSets = append(deleteTargeHostSets, ths)
}
t := allocTargetView()
t.PublicId = targetId
if err := r.reader.LookupByPublicId(ctx, &t); err != nil {
return db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("failed for %s", targetId)))
}
var metadata oplog.Metadata
var target interface{}
switch t.Type {
case TcpTargetType.String():
tcpT := allocTcpTarget()
tcpT.PublicId = t.PublicId
tcpT.Version = targetVersion + 1
target = &tcpT
metadata = tcpT.oplog(oplog.OpType_OP_TYPE_UPDATE)
metadata["op-type"] = append(metadata["op-type"], oplog.OpType_OP_TYPE_DELETE.String())
default:
return db.NoRowsAffected, errors.New(errors.InvalidParameter, op, fmt.Sprintf("%s is an unsupported target type %s", t.PublicId, t.Type))
}
oplogWrapper, err := r.kms.GetWrapper(ctx, t.GetScopeId(), kms.KeyPurposeOplog)
if err != nil {
return db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("unable to get oplog wrapper"))
}
var totalRowsDeleted int
_, err = r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(reader db.Reader, w db.Writer) error {
msgs := make([]*oplog.Message, 0, 2)
targetTicket, err := w.GetTicket(target)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to get ticket"))
}
updatedTarget := target.(Cloneable).Clone()
var targetOplogMsg oplog.Message
rowsUpdated, err := w.Update(ctx, updatedTarget, []string{"Version"}, nil, db.NewOplogMsg(&targetOplogMsg), db.WithVersion(&targetVersion))
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to update target version"))
}
if rowsUpdated != 1 {
return errors.New(errors.MultipleRecords, op, fmt.Sprintf("updated target and %d rows updated", rowsUpdated))
}
msgs = append(msgs, &targetOplogMsg)
hostSetsOplogMsgs := make([]*oplog.Message, 0, len(deleteTargeHostSets))
rowsDeleted, err := w.DeleteItems(ctx, deleteTargeHostSets, db.NewOplogMsgs(&hostSetsOplogMsgs))
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to delete target host sets"))
}
if rowsDeleted != len(deleteTargeHostSets) {
return errors.New(errors.MultipleRecords, op, fmt.Sprintf("target host sets deleted %d did not match request for %d", rowsDeleted, len(deleteTargeHostSets)))
}
totalRowsDeleted += rowsDeleted
msgs = append(msgs, hostSetsOplogMsgs...)
if err := w.WriteOplogEntryWith(ctx, oplogWrapper, targetTicket, metadata, msgs); err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to write oplog"))
}
return nil
},
)
if err != nil {
return db.NoRowsAffected, errors.Wrap(err, op)
}
return totalRowsDeleted, nil
}
// SetTargetHostSets will set the target's host sets. Set add and/or delete
// target host sets as need to reconcile the existing sets with the sets
// requested. If hostSetIds is empty, the target host sets will be cleared. Zero
// is not a valid value for the WithVersion option and will return an error.
func (r *Repository) SetTargetHostSets(ctx context.Context, targetId string, targetVersion uint32, hostSetIds []string, _ ...Option) ([]*TargetSet, []*TargetLibrary, int, error) {
const op = "target.(Repository).SetTargetHostSets"
if targetId == "" {
return nil, nil, db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing target id")
}
if targetVersion == 0 {
return nil, nil, db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing version")
}
t := allocTargetView()
t.PublicId = targetId
if err := r.reader.LookupByPublicId(ctx, &t); err != nil {
return nil, nil, db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("failed for %s", targetId)))
}
// NOTE: calculating that to set can safely happen outside of the write
// transaction since we're using targetVersion to ensure that the only
// operate on the same set of data from these queries that calculate the
// set.
// TODO(mgaffney) 08/2020: Use SQL to calculate changes.
foundThs, err := fetchSets(ctx, r.reader, targetId)
if err != nil {
return nil, nil, db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("unable to search for existing target host sets"))
}
found := map[string]*TargetSet{}
for _, s := range foundThs {
found[s.PublicId] = s
}
addHostSets := make([]interface{}, 0, len(hostSetIds))
for _, id := range hostSetIds {
if _, ok := found[id]; ok {
// found a match, so do nothing (we want to keep it), but remove it
// from found
delete(found, id)
continue
}
hs, err := NewTargetHostSet(targetId, id)
if err != nil {
return nil, nil, db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("unable to create in memory target host set"))
}
addHostSets = append(addHostSets, hs)
}
deleteHostSets := make([]interface{}, 0, len(hostSetIds))
if len(found) > 0 {
for _, s := range found {
hs, err := NewTargetHostSet(targetId, s.PublicId)
if err != nil {
return nil, nil, db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg(" unable to create in memory target host set"))
}
deleteHostSets = append(deleteHostSets, hs)
}
}
if len(addHostSets) == 0 && len(deleteHostSets) == 0 {
return foundThs, nil, db.NoRowsAffected, nil
}
var metadata oplog.Metadata
var target interface{}
switch t.Type {
case TcpTargetType.String():
tcpT := allocTcpTarget()
tcpT.PublicId = t.PublicId
tcpT.Version = targetVersion + 1
target = &tcpT
metadata = tcpT.oplog(oplog.OpType_OP_TYPE_UPDATE)
default:
return nil, nil, db.NoRowsAffected, errors.New(errors.InvalidParameter, op, fmt.Sprintf("%s is an unsupported target type %s", t.PublicId, t.Type))
}
oplogWrapper, err := r.kms.GetWrapper(ctx, t.GetScopeId(), kms.KeyPurposeOplog)
if err != nil {
return nil, nil, db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg("unable to get oplog wrapper"))
}
var totalRowsAffected int
var currentHostSets []*TargetSet
var currentCredLibs []*TargetLibrary
_, err = r.writer.DoTx(
ctx,
db.StdRetryCnt,
db.ExpBackoff{},
func(reader db.Reader, w db.Writer) error {
msgs := make([]*oplog.Message, 0, 2)
targetTicket, err := w.GetTicket(target)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to get ticket"))
}
updatedTarget := target.(Cloneable).Clone()
var targetOplogMsg oplog.Message
rowsUpdated, err := w.Update(ctx, updatedTarget, []string{"Version"}, nil, db.NewOplogMsg(&targetOplogMsg), db.WithVersion(&targetVersion))
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to update target version"))
}
if rowsUpdated != 1 {
return errors.New(errors.MultipleRecords, op, fmt.Sprintf("set target host sets: updated target and %d rows updated", rowsUpdated))
}
msgs = append(msgs, &targetOplogMsg)
// Write the new ones in
if len(addHostSets) > 0 {
hostSetOplogMsgs := make([]*oplog.Message, 0, len(addHostSets))
if err := w.CreateItems(ctx, addHostSets, db.NewOplogMsgs(&hostSetOplogMsgs)); err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to add target host sets"))
}
totalRowsAffected += len(addHostSets)
msgs = append(msgs, hostSetOplogMsgs...)
metadata["op-type"] = append(metadata["op-type"], oplog.OpType_OP_TYPE_CREATE.String())
}
// Anything we didn't take out of found needs to be removed
if len(deleteHostSets) > 0 {
hostSetOplogMsgs := make([]*oplog.Message, 0, len(deleteHostSets))
rowsDeleted, err := w.DeleteItems(ctx, deleteHostSets, db.NewOplogMsgs(&hostSetOplogMsgs))
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to delete target host set"))
}
if rowsDeleted != len(deleteHostSets) {
return errors.New(errors.MultipleRecords, op, fmt.Sprintf("target host sets deleted %d did not match request for %d", rowsDeleted, len(deleteHostSets)))
}
totalRowsAffected += rowsDeleted
msgs = append(msgs, hostSetOplogMsgs...)
metadata["op-type"] = append(metadata["op-type"], oplog.OpType_OP_TYPE_DELETE.String())
}
if err := w.WriteOplogEntryWith(ctx, oplogWrapper, targetTicket, metadata, msgs); err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to write oplog"))
}
currentHostSets, err = fetchSets(ctx, reader, targetId)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to retrieve current target host sets after set"))
}
currentCredLibs, err = fetchLibraries(ctx, reader, targetId)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to retrieve current target credential libraries after set"))
}
return nil
},
)
if err != nil {
return nil, nil, db.NoRowsAffected, errors.Wrap(err, op)
}
return currentHostSets, currentCredLibs, totalRowsAffected, nil
}
func fetchSets(ctx context.Context, r db.Reader, targetId string) ([]*TargetSet, error) {
const op = "target.fetchSets"
var hostSets []*TargetSet
if err := r.SearchWhere(ctx, &hostSets, "target_id = ?", []interface{}{targetId}); err != nil {
return nil, errors.Wrap(err, op)
}
if len(hostSets) == 0 {
return nil, nil
}
return hostSets, nil
}