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>
This commit is contained in:
216 files changed
+38675
-1941
No files matched your search
@@ -3,6 +3,7 @@ package common
|
||||
import (
|
||||
"github.com/hashicorp/boundary/internal/auth/oidc"
|
||||
"github.com/hashicorp/boundary/internal/auth/password"
|
||||
"github.com/hashicorp/boundary/internal/credential/vault"
|
||||
"github.com/hashicorp/boundary/internal/host/static"
|
||||
"github.com/hashicorp/boundary/internal/iam"
|
||||
"github.com/hashicorp/boundary/internal/servers"
|
||||
@@ -11,12 +12,13 @@ import (
|
||||
)
|
||||
|
||||
type (
|
||||
AuthTokenRepoFactory = oidc.AuthTokenRepoFactory
|
||||
IamRepoFactory func() (*iam.Repository, error)
|
||||
OidcAuthRepoFactory = oidc.OidcRepoFactory
|
||||
PasswordAuthRepoFactory func() (*password.Repository, error)
|
||||
ServersRepoFactory func() (*servers.Repository, error)
|
||||
StaticRepoFactory func() (*static.Repository, error)
|
||||
SessionRepoFactory func() (*session.Repository, error)
|
||||
TargetRepoFactory func() (*target.Repository, error)
|
||||
AuthTokenRepoFactory = oidc.AuthTokenRepoFactory
|
||||
VaultCredentialRepoFactory = func() (*vault.Repository, error)
|
||||
IamRepoFactory func() (*iam.Repository, error)
|
||||
OidcAuthRepoFactory = oidc.OidcRepoFactory
|
||||
PasswordAuthRepoFactory func() (*password.Repository, error)
|
||||
ServersRepoFactory func() (*servers.Repository, error)
|
||||
StaticRepoFactory func() (*static.Repository, error)
|
||||
SessionRepoFactory func() (*session.Repository, error)
|
||||
TargetRepoFactory func() (*target.Repository, error)
|
||||
)
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/hashicorp/boundary/internal/auth/password"
|
||||
"github.com/hashicorp/boundary/internal/authtoken"
|
||||
"github.com/hashicorp/boundary/internal/cmd/config"
|
||||
"github.com/hashicorp/boundary/internal/credential/vault"
|
||||
"github.com/hashicorp/boundary/internal/db"
|
||||
"github.com/hashicorp/boundary/internal/host/static"
|
||||
"github.com/hashicorp/boundary/internal/iam"
|
||||
@@ -41,14 +42,15 @@ type Controller struct {
|
||||
workerStatusUpdateTimes *sync.Map
|
||||
|
||||
// Repo factory methods
|
||||
AuthTokenRepoFn common.AuthTokenRepoFactory
|
||||
IamRepoFn common.IamRepoFactory
|
||||
OidcRepoFn common.OidcAuthRepoFactory
|
||||
PasswordAuthRepoFn common.PasswordAuthRepoFactory
|
||||
ServersRepoFn common.ServersRepoFactory
|
||||
SessionRepoFn common.SessionRepoFactory
|
||||
StaticHostRepoFn common.StaticRepoFactory
|
||||
TargetRepoFn common.TargetRepoFactory
|
||||
AuthTokenRepoFn common.AuthTokenRepoFactory
|
||||
VaultCredentialRepoFn common.VaultCredentialRepoFactory
|
||||
IamRepoFn common.IamRepoFactory
|
||||
OidcRepoFn common.OidcAuthRepoFactory
|
||||
PasswordAuthRepoFn common.PasswordAuthRepoFactory
|
||||
ServersRepoFn common.ServersRepoFactory
|
||||
SessionRepoFn common.SessionRepoFactory
|
||||
StaticHostRepoFn common.StaticRepoFactory
|
||||
TargetRepoFn common.TargetRepoFactory
|
||||
|
||||
scheduler *scheduler.Scheduler
|
||||
|
||||
@@ -112,7 +114,6 @@ func New(conf *Config) (*Controller, error) {
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("error adding config keys to kms: %w", err)
|
||||
}
|
||||
|
||||
jobRepoFn := func() (*job.Repository, error) {
|
||||
return job.NewRepository(dbase, dbase, c.kms)
|
||||
}
|
||||
@@ -131,6 +132,9 @@ func New(conf *Config) (*Controller, error) {
|
||||
authtoken.WithTokenTimeToLiveDuration(c.conf.RawConfig.Controller.AuthTokenTimeToLiveDuration),
|
||||
authtoken.WithTokenTimeToStaleDuration(c.conf.RawConfig.Controller.AuthTokenTimeToStaleDuration))
|
||||
}
|
||||
c.VaultCredentialRepoFn = func() (*vault.Repository, error) {
|
||||
return vault.NewRepository(dbase, dbase, c.kms, c.scheduler)
|
||||
}
|
||||
c.ServersRepoFn = func() (*servers.Repository, error) {
|
||||
return servers.NewRepository(dbase, dbase, c.kms)
|
||||
}
|
||||
@@ -163,7 +167,6 @@ func (c *Controller) Start() error {
|
||||
if err := c.scheduler.Start(c.baseContext); err != nil {
|
||||
return fmt.Errorf("error starting scheduler: %w", err)
|
||||
}
|
||||
|
||||
if err := c.startListeners(); err != nil {
|
||||
return fmt.Errorf("error starting controller listeners: %w", err)
|
||||
}
|
||||
@@ -178,7 +181,8 @@ func (c *Controller) Start() error {
|
||||
}
|
||||
|
||||
func (c *Controller) registerJobs() error {
|
||||
return nil
|
||||
rw := db.New(c.conf.Database)
|
||||
return vault.RegisterJobs(c.baseContext, c.scheduler, rw, rw, c.kms, c.logger)
|
||||
}
|
||||
|
||||
func (c *Controller) Shutdown(serversOnly bool) error {
|
||||
|
||||
@@ -20,6 +20,8 @@ import (
|
||||
"github.com/hashicorp/boundary/internal/requests"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/accounts"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/authmethods"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/credentiallibraries"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/credentialstores"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/host_sets"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/managed_groups"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/sessions"
|
||||
@@ -139,7 +141,8 @@ func handleGrpcGateway(c *Controller, props HandlerProperties) (http.Handler, er
|
||||
c.IamRepoFn,
|
||||
c.ServersRepoFn,
|
||||
c.SessionRepoFn,
|
||||
c.StaticHostRepoFn)
|
||||
c.StaticHostRepoFn,
|
||||
c.VaultCredentialRepoFn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create target handler service: %w", err)
|
||||
}
|
||||
@@ -174,6 +177,20 @@ func handleGrpcGateway(c *Controller, props HandlerProperties) (http.Handler, er
|
||||
if err := services.RegisterManagedGroupServiceHandlerServer(ctx, mux, mgs); err != nil {
|
||||
return nil, fmt.Errorf("failed to register managed groups service handler: %w", err)
|
||||
}
|
||||
cs, err := credentialstores.NewService(c.VaultCredentialRepoFn, c.IamRepoFn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create credential store handler service: %w", err)
|
||||
}
|
||||
if err := services.RegisterCredentialStoreServiceHandlerServer(ctx, mux, cs); err != nil {
|
||||
return nil, fmt.Errorf("failed to register credential store service handler: %w", err)
|
||||
}
|
||||
cl, err := credentiallibraries.NewService(c.VaultCredentialRepoFn, c.IamRepoFn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create credential library handler service: %w", err)
|
||||
}
|
||||
if err := services.RegisterCredentialLibraryServiceHandlerServer(ctx, mux, cl); err != nil {
|
||||
return nil, fmt.Errorf("failed to register credential library service handler: %w", err)
|
||||
}
|
||||
|
||||
return mux, nil
|
||||
}
|
||||
|
||||
@@ -106,6 +106,8 @@ func TestHandleImplementedPaths(t *testing.T) {
|
||||
"v1/auth-methods/someid:authenticate:callback",
|
||||
"v1/auth-tokens",
|
||||
"v1/auth-tokens/someid",
|
||||
"v1/credential-stores",
|
||||
"v1/credential-stores/someid",
|
||||
"v1/groups",
|
||||
"v1/groups/someid",
|
||||
"v1/host-catalogs",
|
||||
@@ -130,6 +132,7 @@ func TestHandleImplementedPaths(t *testing.T) {
|
||||
// Creation end points
|
||||
"v1/accounts",
|
||||
"v1/auth-methods",
|
||||
"v1/credential-stores",
|
||||
"v1/groups",
|
||||
"v1/host-catalogs",
|
||||
"v1/host-sets",
|
||||
@@ -169,6 +172,7 @@ func TestHandleImplementedPaths(t *testing.T) {
|
||||
"v1/accounts/someid",
|
||||
"v1/auth-methods/someid",
|
||||
"v1/auth-tokens/someid",
|
||||
"v1/credential-stores/someid",
|
||||
"v1/groups/someid",
|
||||
"v1/host-catalogs/someid",
|
||||
"v1/host-sets/someid",
|
||||
@@ -181,6 +185,7 @@ func TestHandleImplementedPaths(t *testing.T) {
|
||||
"PATCH": {
|
||||
"v1/accounts/someid",
|
||||
"v1/auth-methods/someid",
|
||||
"v1/credential-stores/someid",
|
||||
"v1/groups/someid",
|
||||
"v1/host-catalogs/someid",
|
||||
"v1/host-sets/someid",
|
||||
|
||||
@@ -80,10 +80,10 @@ var (
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if pwMaskManager, err = handlers.NewMaskManager(&pwstore.Account{}, &pb.Account{}, &pb.PasswordAccountAttributes{}); err != nil {
|
||||
if pwMaskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&pwstore.Account{}}, handlers.MaskSource{&pb.Account{}, &pb.PasswordAccountAttributes{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if oidcMaskManager, err = handlers.NewMaskManager(&oidcstore.Account{}, &pb.Account{}, &pb.OidcAccountAttributes{}); err != nil {
|
||||
if oidcMaskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&oidcstore.Account{}}, handlers.MaskSource{&pb.Account{}, &pb.OidcAccountAttributes{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ var oidcMaskManager handlers.MaskManager
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if oidcMaskManager, err = handlers.NewMaskManager(&oidcstore.AuthMethod{}, &pb.AuthMethod{}, &pb.OidcAuthMethodAttributes{}); err != nil {
|
||||
if oidcMaskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&oidcstore.AuthMethod{}}, handlers.MaskSource{&pb.AuthMethod{}, &pb.OidcAuthMethodAttributes{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
|
||||
@@ -148,9 +148,6 @@ func TestList_FilterNonPublic(t *testing.T) {
|
||||
atRepoFn := func() (*authtoken.Repository, error) {
|
||||
return authtoken.NewRepository(rw, rw, kmsCache)
|
||||
}
|
||||
authTokenRepoFn := func() (*authtoken.Repository, error) {
|
||||
return authtoken.NewRepository(rw, rw, kmsCache)
|
||||
}
|
||||
serversRepoFn := func() (*servers.Repository, error) {
|
||||
return servers.NewRepository(rw, rw, kmsCache)
|
||||
}
|
||||
@@ -206,7 +203,7 @@ func TestList_FilterNonPublic(t *testing.T) {
|
||||
return auth.NewVerifierContext(requests.NewRequestContext(context.Background()),
|
||||
nil,
|
||||
iamRepoFn,
|
||||
authTokenRepoFn,
|
||||
atRepoFn,
|
||||
serversRepoFn,
|
||||
kmsCache,
|
||||
auth.RequestInfo{
|
||||
|
||||
@@ -28,7 +28,7 @@ var pwMaskManager handlers.MaskManager
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if pwMaskManager, err = handlers.NewMaskManager(&pwstore.AuthMethod{}, &pb.AuthMethod{}, &pb.PasswordAuthMethodAttributes{}); err != nil {
|
||||
if pwMaskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&pwstore.AuthMethod{}}, handlers.MaskSource{&pb.AuthMethod{}, &pb.PasswordAuthMethodAttributes{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
|
||||
+602
@@ -0,0 +1,602 @@
|
||||
package credentiallibraries
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/boundary/globals"
|
||||
"github.com/hashicorp/boundary/internal/auth"
|
||||
"github.com/hashicorp/boundary/internal/credential"
|
||||
"github.com/hashicorp/boundary/internal/credential/vault"
|
||||
"github.com/hashicorp/boundary/internal/credential/vault/store"
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/credentiallibraries"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/boundary/internal/perms"
|
||||
"github.com/hashicorp/boundary/internal/requests"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/common"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers"
|
||||
"github.com/hashicorp/boundary/internal/types/action"
|
||||
"github.com/hashicorp/boundary/internal/types/resource"
|
||||
"github.com/hashicorp/boundary/sdk/strutil"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/protobuf/types/known/wrapperspb"
|
||||
)
|
||||
|
||||
const (
|
||||
vaultPathField = "attributes.path"
|
||||
httpMethodField = "attributes.http_method"
|
||||
httpRequestBodyField = "attributes.http_request_body"
|
||||
)
|
||||
|
||||
var (
|
||||
maskManager handlers.MaskManager
|
||||
|
||||
// IdActions contains the set of actions that can be performed on
|
||||
// individual resources
|
||||
IdActions = action.ActionSet{
|
||||
action.NoOp,
|
||||
action.Read,
|
||||
action.Update,
|
||||
action.Delete,
|
||||
}
|
||||
|
||||
// CollectionActions contains the set of actions that can be performed on
|
||||
// this collection
|
||||
CollectionActions = action.ActionSet{
|
||||
action.Create,
|
||||
action.List,
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if maskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&store.CredentialLibrary{}},
|
||||
handlers.MaskSource{&pb.CredentialLibrary{}, &pb.VaultCredentialLibraryAttributes{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Service handles request as described by the pbs.CredentialLibraryServiceServer interface.
|
||||
type Service struct {
|
||||
pbs.UnimplementedCredentialLibraryServiceServer
|
||||
|
||||
iamRepoFn common.IamRepoFactory
|
||||
repoFn common.VaultCredentialRepoFactory
|
||||
}
|
||||
|
||||
// NewService returns a credential library service which handles credential library related requests to boundary.
|
||||
func NewService(repo common.VaultCredentialRepoFactory, iamRepo common.IamRepoFactory) (Service, error) {
|
||||
const op = "credentiallibraries.NewService"
|
||||
if iamRepo == nil {
|
||||
return Service{}, errors.New(errors.InvalidParameter, op, "missing iam repository")
|
||||
}
|
||||
if repo == nil {
|
||||
return Service{}, errors.New(errors.InvalidParameter, op, "missing vault credential repository")
|
||||
}
|
||||
return Service{iamRepoFn: iamRepo, repoFn: repo}, nil
|
||||
}
|
||||
|
||||
var _ pbs.CredentialLibraryServiceServer = Service{}
|
||||
|
||||
// ListCredentialLibraries implements the interface pbs.CredentialLibraryServiceServer
|
||||
func (s Service) ListCredentialLibraries(ctx context.Context, req *pbs.ListCredentialLibrariesRequest) (*pbs.ListCredentialLibrariesResponse, error) {
|
||||
if err := validateListRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetCredentialStoreId(), action.List)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
|
||||
csl, err := s.listFromRepo(ctx, req.GetCredentialStoreId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(csl) == 0 {
|
||||
return &pbs.ListCredentialLibrariesResponse{}, nil
|
||||
}
|
||||
|
||||
filter, err := handlers.NewFilter(req.GetFilter())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
finalItems := make([]*pb.CredentialLibrary, 0, len(csl))
|
||||
res := perms.Resource{
|
||||
ScopeId: authResults.Scope.Id,
|
||||
Type: resource.CredentialLibrary,
|
||||
Pin: req.GetCredentialStoreId(),
|
||||
}
|
||||
for _, item := range csl {
|
||||
res.Id = item.GetPublicId()
|
||||
authorizedActions := authResults.FetchActionSetForId(ctx, item.GetPublicId(), IdActions, auth.WithResource(&res)).Strings()
|
||||
if len(authorizedActions) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
outputFields := authResults.FetchOutputFields(res, action.List).SelfOrDefaults(authResults.UserId)
|
||||
outputOpts := make([]handlers.Option, 0, 3)
|
||||
outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields))
|
||||
if outputFields.Has(globals.ScopeField) {
|
||||
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedActionsField) {
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authorizedActions))
|
||||
}
|
||||
|
||||
item, err := toProto(item, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if filter.Match(item) {
|
||||
finalItems = append(finalItems, item)
|
||||
}
|
||||
}
|
||||
return &pbs.ListCredentialLibrariesResponse{Items: finalItems}, nil
|
||||
}
|
||||
|
||||
// GetCredentialLibrary implements the interface pbs.CredentialLibraryServiceServer.
|
||||
func (s Service) GetCredentialLibrary(ctx context.Context, req *pbs.GetCredentialLibraryRequest) (*pbs.GetCredentialLibraryResponse, error) {
|
||||
const op = "credentiallibraries.(Service).GetCredentialLibrary"
|
||||
|
||||
if err := validateGetRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetId(), action.Read)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
cs, err := s.getFromRepo(ctx, req.GetId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputFields, ok := requests.OutputFields(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New(errors.Internal, op, "no request context found")
|
||||
}
|
||||
|
||||
outputOpts := make([]handlers.Option, 0, 3)
|
||||
outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields))
|
||||
if outputFields.Has(globals.ScopeField) {
|
||||
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedActionsField) {
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, cs.GetPublicId(), IdActions).Strings()))
|
||||
}
|
||||
|
||||
item, err := toProto(cs, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &pbs.GetCredentialLibraryResponse{Item: item}, nil
|
||||
}
|
||||
|
||||
// CreateCredentialLibrary implements the interface pbs.CredentialLibraryServiceServer.
|
||||
func (s Service) CreateCredentialLibrary(ctx context.Context, req *pbs.CreateCredentialLibraryRequest) (*pbs.CreateCredentialLibraryResponse, error) {
|
||||
const op = "credentiallibraries.(Service).CreateCredentialLibrary"
|
||||
|
||||
if err := validateCreateRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetItem().GetCredentialStoreId(), action.Create)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
cl, err := s.createInRepo(ctx, authResults.Scope.GetId(), req.GetItem())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputFields, ok := requests.OutputFields(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New(errors.Internal, op, "no request context found")
|
||||
}
|
||||
|
||||
outputOpts := make([]handlers.Option, 0, 3)
|
||||
outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields))
|
||||
if outputFields.Has(globals.ScopeField) {
|
||||
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedActionsField) {
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, cl.GetPublicId(), IdActions).Strings()))
|
||||
}
|
||||
|
||||
item, err := toProto(cl, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &pbs.CreateCredentialLibraryResponse{
|
||||
Item: item,
|
||||
Uri: fmt.Sprintf("credential-libraries/%s", item.GetId()),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UpdateCredentialLibrary implements the interface pbs.CredentialLibraryServiceServer.
|
||||
func (s Service) UpdateCredentialLibrary(ctx context.Context, req *pbs.UpdateCredentialLibraryRequest) (*pbs.UpdateCredentialLibraryResponse, error) {
|
||||
const op = "credentiallibraries.(Service).UpdateCredentialLibrary"
|
||||
|
||||
if err := validateUpdateRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetId(), action.Update)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
cl, err := s.updateInRepo(ctx, authResults.Scope.GetId(), req.GetId(), req.GetUpdateMask().GetPaths(), req.GetItem())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputFields, ok := requests.OutputFields(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New(errors.Internal, op, "no request context found")
|
||||
}
|
||||
|
||||
outputOpts := make([]handlers.Option, 0, 3)
|
||||
outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields))
|
||||
if outputFields.Has(globals.ScopeField) {
|
||||
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedActionsField) {
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, cl.GetPublicId(), IdActions).Strings()))
|
||||
}
|
||||
|
||||
item, err := toProto(cl, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &pbs.UpdateCredentialLibraryResponse{Item: item}, nil
|
||||
}
|
||||
|
||||
// DeleteCredentialLibrary implements the interface pbs.CredentialLibraryServiceServer.
|
||||
func (s Service) DeleteCredentialLibrary(ctx context.Context, req *pbs.DeleteCredentialLibraryRequest) (*pbs.DeleteCredentialLibraryResponse, error) {
|
||||
if err := validateDeleteRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetId(), action.Delete)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
_, err := s.deleteFromRepo(ctx, authResults.Scope.GetId(), req.GetId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s Service) listFromRepo(ctx context.Context, storeId string) ([]*vault.CredentialLibrary, error) {
|
||||
const op = "credentiallibraries.(Service).listFromRepo"
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
csl, err := repo.ListCredentialLibraries(ctx, storeId)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
return csl, nil
|
||||
}
|
||||
|
||||
func (s Service) getFromRepo(ctx context.Context, id string) (credential.Library, error) {
|
||||
const op = "credentiallibraries.(Service).getFromRepo"
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
cs, err := repo.LookupCredentialLibrary(ctx, id)
|
||||
if err != nil && !errors.IsNotFoundError(err) {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
if cs == nil {
|
||||
return nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("credential library %q not found", id))
|
||||
}
|
||||
return cs, err
|
||||
}
|
||||
|
||||
func (s Service) createInRepo(ctx context.Context, scopeId string, item *pb.CredentialLibrary) (credential.Library, error) {
|
||||
const op = "credentiallibraries.(Service).createInRepo"
|
||||
cl, err := toStorageVaultLibrary(item.GetCredentialStoreId(), item)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
out, err := repo.CreateCredentialLibrary(ctx, scopeId, cl)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op, errors.WithMsg("unable to create credential library"))
|
||||
}
|
||||
if out == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create credential library but no error returned from repository.")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s Service) updateInRepo(ctx context.Context, projId, id string, mask []string, item *pb.CredentialLibrary) (credential.Library, error) {
|
||||
const op = "credentiallibraries.(Service).updateInRepo"
|
||||
cl, err := toStorageVaultLibrary(item.GetCredentialStoreId(), item)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
cl.PublicId = id
|
||||
|
||||
dbMask := maskManager.Translate(mask)
|
||||
if len(dbMask) == 0 {
|
||||
return nil, handlers.InvalidArgumentErrorf("No valid fields included in the update mask.", map[string]string{"update_mask": "No valid fields provided in the update mask."})
|
||||
}
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
out, rowsUpdated, err := repo.UpdateCredentialLibrary(ctx, projId, cl, item.GetVersion(), dbMask)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op, errors.WithMsg("unable to update credential library"))
|
||||
}
|
||||
if rowsUpdated == 0 {
|
||||
return nil, handlers.NotFoundErrorf("Credential Library %q doesn't exist or incorrect version provided.", id)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s Service) deleteFromRepo(ctx context.Context, scopeId, id string) (bool, error) {
|
||||
const op = "credentiallibraries.(Service).deleteFromRepo"
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
rows, err := repo.DeleteCredentialLibrary(ctx, scopeId, id)
|
||||
if err != nil {
|
||||
if errors.IsNotFoundError(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, errors.Wrap(err, op, errors.WithMsg("unable to delete credential library"))
|
||||
}
|
||||
return rows > 0, nil
|
||||
}
|
||||
|
||||
func (s Service) authResult(ctx context.Context, id string, a action.Type) auth.VerifyResults {
|
||||
const op = "credentiallibraries.(Service).authResult"
|
||||
res := auth.VerifyResults{}
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return res
|
||||
}
|
||||
|
||||
var parentId string
|
||||
opts := []auth.Option{auth.WithType(resource.CredentialLibrary), auth.WithAction(a)}
|
||||
switch a {
|
||||
case action.List, action.Create:
|
||||
parentId = id
|
||||
default:
|
||||
opts = append(opts, auth.WithId(id))
|
||||
|
||||
switch credential.SubtypeFromId(id) {
|
||||
case credential.VaultSubtype:
|
||||
cl, err := repo.LookupCredentialLibrary(ctx, id)
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return res
|
||||
}
|
||||
if cl == nil {
|
||||
res.Error = handlers.NotFoundError()
|
||||
return res
|
||||
}
|
||||
parentId = cl.GetStoreId()
|
||||
default:
|
||||
res.Error = errors.New(errors.InvalidParameter, op, "unrecognized credential library subtype from id")
|
||||
return res
|
||||
}
|
||||
}
|
||||
|
||||
if parentId == "" {
|
||||
res.Error = errors.New(errors.RecordNotFound, op, "unable to find credential store for provided library")
|
||||
return res
|
||||
}
|
||||
|
||||
opts = append(opts, auth.WithPin(parentId))
|
||||
|
||||
switch credential.SubtypeFromId(parentId) {
|
||||
case credential.VaultSubtype:
|
||||
cs, err := repo.LookupCredentialStore(ctx, parentId)
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return res
|
||||
}
|
||||
if cs == nil {
|
||||
res.Error = handlers.NotFoundError()
|
||||
return res
|
||||
}
|
||||
opts = append(opts, auth.WithScopeId(cs.GetScopeId()))
|
||||
default:
|
||||
res.Error = errors.New(errors.InvalidParameter, op, "unrecognized credential store subtype from id")
|
||||
return res
|
||||
}
|
||||
|
||||
return auth.Verify(ctx, opts...)
|
||||
}
|
||||
|
||||
func toProto(in credential.Library, opt ...handlers.Option) (*pb.CredentialLibrary, error) {
|
||||
const op = "credentiallibraries.toProto"
|
||||
|
||||
opts := handlers.GetOpts(opt...)
|
||||
if opts.WithOutputFields == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "output fields not found when building credential library proto")
|
||||
}
|
||||
outputFields := *opts.WithOutputFields
|
||||
|
||||
out := pb.CredentialLibrary{}
|
||||
if outputFields.Has(globals.IdField) {
|
||||
out.Id = in.GetPublicId()
|
||||
}
|
||||
if outputFields.Has(globals.CredentialStoreIdField) {
|
||||
out.CredentialStoreId = in.GetStoreId()
|
||||
}
|
||||
if outputFields.Has(globals.TypeField) {
|
||||
out.Type = credential.SubtypeFromId(in.GetPublicId()).String()
|
||||
}
|
||||
if outputFields.Has(globals.DescriptionField) && in.GetDescription() != "" {
|
||||
out.Description = wrapperspb.String(in.GetDescription())
|
||||
}
|
||||
if outputFields.Has(globals.NameField) && in.GetName() != "" {
|
||||
out.Name = wrapperspb.String(in.GetName())
|
||||
}
|
||||
if outputFields.Has(globals.CreatedTimeField) {
|
||||
out.CreatedTime = in.GetCreateTime().GetTimestamp()
|
||||
}
|
||||
if outputFields.Has(globals.UpdatedTimeField) {
|
||||
out.UpdatedTime = in.GetUpdateTime().GetTimestamp()
|
||||
}
|
||||
if outputFields.Has(globals.VersionField) {
|
||||
out.Version = in.GetVersion()
|
||||
}
|
||||
if outputFields.Has(globals.ScopeField) {
|
||||
out.Scope = opts.WithScope
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedActionsField) {
|
||||
out.AuthorizedActions = opts.WithAuthorizedActions
|
||||
}
|
||||
if outputFields.Has(globals.AttributesField) {
|
||||
switch credential.SubtypeFromId(in.GetPublicId()) {
|
||||
case credential.VaultSubtype:
|
||||
vaultIn, ok := in.(*vault.CredentialLibrary)
|
||||
if !ok {
|
||||
return nil, errors.New(errors.Internal, op, "unable to cast to vault credential library")
|
||||
}
|
||||
attrs := &pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String(vaultIn.GetVaultPath()),
|
||||
}
|
||||
if vaultIn.GetHttpMethod() != "" {
|
||||
attrs.HttpMethod = wrapperspb.String(vaultIn.GetHttpMethod())
|
||||
}
|
||||
if vaultIn.GetHttpRequestBody() != nil {
|
||||
attrs.HttpRequestBody = wrapperspb.String(string(vaultIn.GetHttpRequestBody()))
|
||||
}
|
||||
var err error
|
||||
out.Attributes, err = handlers.ProtoToStruct(attrs)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op, errors.WithMsg("failed to convert resource from storage to api"))
|
||||
}
|
||||
}
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func toStorageVaultLibrary(storeId string, in *pb.CredentialLibrary) (out *vault.CredentialLibrary, err error) {
|
||||
const op = "credentiallibraries.toStorageVaultLibrary"
|
||||
var opts []vault.Option
|
||||
if in.GetName() != nil {
|
||||
opts = append(opts, vault.WithName(in.GetName().GetValue()))
|
||||
}
|
||||
if in.GetDescription() != nil {
|
||||
opts = append(opts, vault.WithDescription(in.GetDescription().GetValue()))
|
||||
}
|
||||
|
||||
attrs := &pb.VaultCredentialLibraryAttributes{}
|
||||
if err := handlers.StructToProto(in.GetAttributes(), attrs); err != nil {
|
||||
return nil, errors.Wrap(err, op, errors.WithMsg("unable to parse the attributes"))
|
||||
}
|
||||
|
||||
if attrs.GetHttpMethod() != nil {
|
||||
opts = append(opts, vault.WithMethod(vault.Method(strings.ToUpper(attrs.GetHttpMethod().GetValue()))))
|
||||
}
|
||||
if attrs.GetHttpRequestBody() != nil {
|
||||
opts = append(opts, vault.WithRequestBody([]byte(attrs.GetHttpRequestBody().GetValue())))
|
||||
}
|
||||
|
||||
cs, err := vault.NewCredentialLibrary(storeId, attrs.GetPath().GetValue(), opts...)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op, errors.WithMsg("unable to build credential library"))
|
||||
}
|
||||
return cs, err
|
||||
}
|
||||
|
||||
// A validateX method should exist for each method above. These methods do not make calls to any backing service but enforce
|
||||
// requirements on the structure of the request. They verify that:
|
||||
// * The path passed in is correctly formatted
|
||||
// * All required parameters are set
|
||||
// * There are no conflicting parameters provided
|
||||
func validateGetRequest(req *pbs.GetCredentialLibraryRequest) error {
|
||||
return handlers.ValidateGetRequest(handlers.NoopValidatorFn, req, vault.CredentialLibraryPrefix)
|
||||
}
|
||||
|
||||
func validateCreateRequest(req *pbs.CreateCredentialLibraryRequest) error {
|
||||
return handlers.ValidateCreateRequest(req.GetItem(), func() map[string]string {
|
||||
badFields := map[string]string{}
|
||||
switch credential.SubtypeFromId(req.GetItem().GetCredentialStoreId()) {
|
||||
case credential.VaultSubtype:
|
||||
if t := req.GetItem().GetType(); t != "" && credential.SubtypeFromType(t) != credential.VaultSubtype {
|
||||
badFields[globals.CredentialStoreIdField] = "If included, type must match that of the credential store."
|
||||
}
|
||||
attrs := &pb.VaultCredentialLibraryAttributes{}
|
||||
if err := handlers.StructToProto(req.GetItem().GetAttributes(), attrs); err != nil {
|
||||
badFields[globals.AttributesField] = "Attribute fields do not match the expected format."
|
||||
break
|
||||
}
|
||||
if attrs.GetPath().GetValue() == "" {
|
||||
badFields[vaultPathField] = "This is a required field."
|
||||
}
|
||||
if m := attrs.GetHttpMethod(); m != nil && !strutil.StrListContains([]string{"GET", "POST"}, strings.ToUpper(m.GetValue())) {
|
||||
badFields[httpMethodField] = "If set, value must be 'GET' or 'POST'."
|
||||
}
|
||||
if b := attrs.GetHttpRequestBody(); b != nil && strings.ToUpper(attrs.GetHttpMethod().GetValue()) != "POST" {
|
||||
badFields[httpRequestBodyField] = fmt.Sprintf("Field can only be set if %q is set to the value 'POST'.", httpMethodField)
|
||||
}
|
||||
default:
|
||||
badFields[globals.CredentialStoreIdField] = "This field must be a valid credential store id."
|
||||
}
|
||||
return badFields
|
||||
})
|
||||
}
|
||||
|
||||
func validateUpdateRequest(req *pbs.UpdateCredentialLibraryRequest) error {
|
||||
return handlers.ValidateUpdateRequest(req, req.GetItem(), func() map[string]string {
|
||||
badFields := map[string]string{}
|
||||
switch credential.SubtypeFromId(req.GetId()) {
|
||||
case credential.VaultSubtype:
|
||||
if req.GetItem().GetType() != "" && credential.SubtypeFromType(req.GetItem().GetType()) != credential.VaultSubtype {
|
||||
badFields[globals.TypeField] = "Cannot modify resource type."
|
||||
}
|
||||
attrs := &pb.VaultCredentialLibraryAttributes{}
|
||||
if err := handlers.StructToProto(req.GetItem().GetAttributes(), attrs); err != nil {
|
||||
badFields[globals.AttributesField] = "Attribute fields do not match the expected format."
|
||||
break
|
||||
}
|
||||
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), vaultPathField) && attrs.GetPath().GetValue() == "" {
|
||||
badFields[vaultPathField] = "This is a required field and cannot be set to empty."
|
||||
}
|
||||
if m := attrs.GetHttpMethod(); handlers.MaskContains(req.GetUpdateMask().GetPaths(), httpMethodField) && m != nil && !strutil.StrListContains([]string{"GET", "POST"}, strings.ToUpper(m.GetValue())) {
|
||||
badFields[httpMethodField] = "If set, value must be 'GET' or 'POST'."
|
||||
}
|
||||
if b := attrs.GetHttpRequestBody(); b != nil && strings.ToUpper(attrs.GetHttpMethod().GetValue()) == "GET" {
|
||||
badFields[httpRequestBodyField] = fmt.Sprintf("Field can only be set if %q is set to the value 'POST'.", httpMethodField)
|
||||
}
|
||||
}
|
||||
return badFields
|
||||
}, vault.CredentialLibraryPrefix)
|
||||
}
|
||||
|
||||
func validateDeleteRequest(req *pbs.DeleteCredentialLibraryRequest) error {
|
||||
return handlers.ValidateDeleteRequest(handlers.NoopValidatorFn, req, vault.CredentialLibraryPrefix)
|
||||
}
|
||||
|
||||
func validateListRequest(req *pbs.ListCredentialLibrariesRequest) error {
|
||||
badFields := map[string]string{}
|
||||
if !handlers.ValidId(handlers.Id(req.GetCredentialStoreId()), vault.CredentialStorePrefix) {
|
||||
badFields[globals.CredentialStoreIdField] = "This field must be a valid credential store id."
|
||||
}
|
||||
if _, err := handlers.NewFilter(req.GetFilter()); err != nil {
|
||||
badFields["filter"] = fmt.Sprintf("This field could not be parsed. %v", err)
|
||||
}
|
||||
if len(badFields) > 0 {
|
||||
return handlers.InvalidArgumentErrorf("Improperly formatted identifier.", badFields)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+881
@@ -0,0 +1,881 @@
|
||||
package credentiallibraries
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/boundary/internal/auth"
|
||||
"github.com/hashicorp/boundary/internal/credential"
|
||||
"github.com/hashicorp/boundary/internal/credential/vault"
|
||||
"github.com/hashicorp/boundary/internal/db"
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/credentiallibraries"
|
||||
scopepb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/scopes"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/boundary/internal/host/static"
|
||||
"github.com/hashicorp/boundary/internal/iam"
|
||||
"github.com/hashicorp/boundary/internal/kms"
|
||||
"github.com/hashicorp/boundary/internal/scheduler"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers"
|
||||
"github.com/hashicorp/boundary/internal/types/scope"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/protobuf/proto"
|
||||
"google.golang.org/protobuf/testing/protocmp"
|
||||
"google.golang.org/protobuf/types/known/fieldmaskpb"
|
||||
"google.golang.org/protobuf/types/known/structpb"
|
||||
"google.golang.org/protobuf/types/known/timestamppb"
|
||||
"google.golang.org/protobuf/types/known/wrapperspb"
|
||||
)
|
||||
|
||||
var testAuthorizedActions = []string{"no-op", "read", "update", "delete"}
|
||||
|
||||
func TestList(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
sche := scheduler.TestScheduler(t, conn, wrapper)
|
||||
rw := db.New(conn)
|
||||
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iamRepo, nil
|
||||
}
|
||||
repoFn := func() (*vault.Repository, error) {
|
||||
return vault.NewRepository(rw, rw, kms, sche)
|
||||
}
|
||||
|
||||
_, prjNoLibs := iam.TestScopes(t, iamRepo)
|
||||
storeNoLibs := vault.TestCredentialStores(t, conn, wrapper, prjNoLibs.GetPublicId(), 1)[0]
|
||||
_, prj := iam.TestScopes(t, iamRepo)
|
||||
|
||||
store := vault.TestCredentialStores(t, conn, wrapper, prj.GetPublicId(), 1)[0]
|
||||
var wantLibraries []*pb.CredentialLibrary
|
||||
for _, l := range vault.TestCredentialLibraries(t, conn, wrapper, store.GetPublicId(), 10) {
|
||||
wantLibraries = append(wantLibraries, &pb.CredentialLibrary{
|
||||
Id: l.GetPublicId(),
|
||||
CredentialStoreId: l.GetStoreId(),
|
||||
Scope: &scopepb.ScopeInfo{Id: prj.GetPublicId(), Type: scope.Project.String(), ParentScopeId: prj.GetParentId()},
|
||||
CreatedTime: l.GetCreateTime().GetTimestamp(),
|
||||
UpdatedTime: l.GetUpdateTime().GetTimestamp(),
|
||||
Version: l.GetVersion(),
|
||||
Type: credential.VaultSubtype.String(),
|
||||
AuthorizedActions: testAuthorizedActions,
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String(l.GetVaultPath()),
|
||||
HttpMethod: wrapperspb.String(l.GetHttpMethod()),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
})
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
req *pbs.ListCredentialLibrariesRequest
|
||||
res *pbs.ListCredentialLibrariesResponse
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "List Many Libraries",
|
||||
req: &pbs.ListCredentialLibrariesRequest{CredentialStoreId: store.GetPublicId()},
|
||||
res: &pbs.ListCredentialLibrariesResponse{Items: wantLibraries},
|
||||
},
|
||||
{
|
||||
name: "List No Libraries",
|
||||
req: &pbs.ListCredentialLibrariesRequest{CredentialStoreId: storeNoLibs.GetPublicId()},
|
||||
res: &pbs.ListCredentialLibrariesResponse{},
|
||||
},
|
||||
{
|
||||
name: "Filter to One Libraries",
|
||||
req: &pbs.ListCredentialLibrariesRequest{CredentialStoreId: store.GetPublicId(), Filter: fmt.Sprintf(`"/item/id"==%q`, wantLibraries[1].GetId())},
|
||||
res: &pbs.ListCredentialLibrariesResponse{Items: wantLibraries[1:2]},
|
||||
},
|
||||
{
|
||||
name: "Filter to No Libraries",
|
||||
req: &pbs.ListCredentialLibrariesRequest{CredentialStoreId: store.GetPublicId(), Filter: `"/item/id"=="doesnt match"`},
|
||||
res: &pbs.ListCredentialLibrariesResponse{},
|
||||
},
|
||||
{
|
||||
name: "Filter Bad Format",
|
||||
req: &pbs.ListCredentialLibrariesRequest{CredentialStoreId: store.GetPublicId(), Filter: `"//id/"=="bad"`},
|
||||
err: handlers.InvalidArgumentErrorf("bad format", nil),
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s, err := NewService(repoFn, iamRepoFn)
|
||||
require.NoError(t, err, "Couldn't create new host set service.")
|
||||
|
||||
// Test non-anonymous listing
|
||||
got, gErr := s.ListCredentialLibraries(auth.DisabledAuthTestContext(iamRepoFn, prj.GetPublicId()), tc.req)
|
||||
if tc.err != nil {
|
||||
require.Error(t, gErr)
|
||||
assert.True(t, errors.Is(gErr, tc.err), "ListCredentialLibrary(%q) got error %v, wanted %v", tc.req, gErr, tc.err)
|
||||
return
|
||||
}
|
||||
require.NoError(t, gErr)
|
||||
sort.Slice(got.Items, func(i, j int) bool {
|
||||
return got.Items[i].GetId() < got.Items[j].GetId()
|
||||
})
|
||||
want := proto.Clone(tc.res).(*pbs.ListCredentialLibrariesResponse)
|
||||
sort.Slice(want.Items, func(i, j int) bool {
|
||||
return want.Items[i].GetId() < want.Items[j].GetId()
|
||||
})
|
||||
assert.Empty(t, cmp.Diff(got, want, protocmp.Transform()))
|
||||
|
||||
// Test anonymous listing
|
||||
got, gErr = s.ListCredentialLibraries(auth.DisabledAuthTestContext(iamRepoFn, prj.GetPublicId(), auth.WithUserId(auth.AnonymousUserId)), tc.req)
|
||||
require.NoError(t, gErr)
|
||||
assert.Len(t, got.Items, len(tc.res.Items))
|
||||
for _, item := range got.GetItems() {
|
||||
require.Nil(t, item.CreatedTime)
|
||||
require.Nil(t, item.UpdatedTime)
|
||||
require.Zero(t, item.Version)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreate(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
sche := scheduler.TestScheduler(t, conn, wrapper)
|
||||
rw := db.New(conn)
|
||||
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iamRepo, nil
|
||||
}
|
||||
repoFn := func() (*vault.Repository, error) {
|
||||
return vault.NewRepository(rw, rw, kms, sche)
|
||||
}
|
||||
|
||||
_, prj := iam.TestScopes(t, iamRepo)
|
||||
store := vault.TestCredentialStores(t, conn, wrapper, prj.GetPublicId(), 1)[0]
|
||||
defaultCL := vault.TestCredentialLibraries(t, conn, wrapper, store.GetPublicId(), 1)[0]
|
||||
defaultCreated := defaultCL.GetCreateTime().GetTimestamp()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
req *pbs.CreateCredentialLibraryRequest
|
||||
res *pbs.CreateCredentialLibraryResponse
|
||||
idPrefix string
|
||||
err error
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "missing vault path",
|
||||
req: &pbs.CreateCredentialLibraryRequest{Item: &pb.CredentialLibrary{
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
}},
|
||||
idPrefix: vault.CredentialLibraryPrefix + "_",
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "Can't specify Id",
|
||||
req: &pbs.CreateCredentialLibraryRequest{Item: &pb.CredentialLibrary{
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
Id: vault.CredentialLibraryPrefix + "_notallowed",
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String("something"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
}},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Can't specify Created Time",
|
||||
req: &pbs.CreateCredentialLibraryRequest{Item: &pb.CredentialLibrary{
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
CreatedTime: timestamppb.Now(),
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String("something"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
}},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Can't specify Update Time",
|
||||
req: &pbs.CreateCredentialLibraryRequest{Item: &pb.CredentialLibrary{
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
UpdatedTime: timestamppb.Now(),
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String("something"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
}},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Type and parent id must match",
|
||||
req: &pbs.CreateCredentialLibraryRequest{Item: &pb.CredentialLibrary{
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
Type: "static",
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String("something"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
}},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "parent id must be included",
|
||||
req: &pbs.CreateCredentialLibraryRequest{Item: &pb.CredentialLibrary{
|
||||
Type: credential.VaultSubtype.String(),
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String("something"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
}},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Attributes must be valid for vault type",
|
||||
req: &pbs.CreateCredentialLibraryRequest{Item: &pb.CredentialLibrary{
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String("something"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
attrs.Fields["invalid"] = structpb.NewStringValue("foo")
|
||||
return attrs
|
||||
}(),
|
||||
}},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Cannot specify a http request body when http method is get",
|
||||
req: &pbs.CreateCredentialLibraryRequest{Item: &pb.CredentialLibrary{
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String("something"),
|
||||
HttpRequestBody: wrapperspb.String("foo"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
}},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Invalid Method",
|
||||
req: &pbs.CreateCredentialLibraryRequest{Item: &pb.CredentialLibrary{
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String("something"),
|
||||
HttpMethod: wrapperspb.String("PATCH"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
}},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Request Body With GET Method",
|
||||
req: &pbs.CreateCredentialLibraryRequest{Item: &pb.CredentialLibrary{
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String("something"),
|
||||
HttpRequestBody: wrapperspb.String("foo"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
}},
|
||||
res: nil,
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Using POST method",
|
||||
req: &pbs.CreateCredentialLibraryRequest{Item: &pb.CredentialLibrary{
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String("something"),
|
||||
HttpMethod: wrapperspb.String("post"),
|
||||
HttpRequestBody: wrapperspb.String("foo"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
}},
|
||||
idPrefix: vault.CredentialLibraryPrefix + "_",
|
||||
res: &pbs.CreateCredentialLibraryResponse{
|
||||
Uri: fmt.Sprintf("credential-libraries/%s_", vault.CredentialLibraryPrefix),
|
||||
Item: &pb.CredentialLibrary{
|
||||
Id: store.GetPublicId(),
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
CreatedTime: store.GetCreateTime().GetTimestamp(),
|
||||
UpdatedTime: store.GetUpdateTime().GetTimestamp(),
|
||||
Scope: &scopepb.ScopeInfo{Id: prj.GetPublicId(), Type: prj.GetType(), ParentScopeId: prj.GetParentId()},
|
||||
Version: 1,
|
||||
Type: credential.VaultSubtype.String(),
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String("something"),
|
||||
HttpMethod: wrapperspb.String("POST"),
|
||||
HttpRequestBody: wrapperspb.String("foo"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
AuthorizedActions: testAuthorizedActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "Create a valid vault CredentialLibrary",
|
||||
req: &pbs.CreateCredentialLibraryRequest{Item: &pb.CredentialLibrary{
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
Name: &wrapperspb.StringValue{Value: "name"},
|
||||
Description: &wrapperspb.StringValue{Value: "desc"},
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String("something"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
}},
|
||||
idPrefix: vault.CredentialLibraryPrefix + "_",
|
||||
res: &pbs.CreateCredentialLibraryResponse{
|
||||
Uri: fmt.Sprintf("credential-libraries/%s_", vault.CredentialLibraryPrefix),
|
||||
Item: &pb.CredentialLibrary{
|
||||
Id: store.GetPublicId(),
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
CreatedTime: store.GetCreateTime().GetTimestamp(),
|
||||
UpdatedTime: store.GetUpdateTime().GetTimestamp(),
|
||||
Name: &wrapperspb.StringValue{Value: "name"},
|
||||
Description: &wrapperspb.StringValue{Value: "desc"},
|
||||
Scope: &scopepb.ScopeInfo{Id: prj.GetPublicId(), Type: prj.GetType(), ParentScopeId: prj.GetParentId()},
|
||||
Version: 1,
|
||||
Type: credential.VaultSubtype.String(),
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String("something"),
|
||||
HttpMethod: wrapperspb.String("GET"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
AuthorizedActions: testAuthorizedActions,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
|
||||
s, err := NewService(repoFn, iamRepoFn)
|
||||
require.NoError(err, "Error when getting new credential store service.")
|
||||
|
||||
got, gErr := s.CreateCredentialLibrary(auth.DisabledAuthTestContext(iamRepoFn, prj.GetPublicId()), tc.req)
|
||||
if tc.wantErr || tc.err != nil {
|
||||
require.Error(gErr)
|
||||
if tc.err != nil {
|
||||
assert.True(errors.Is(gErr, tc.err), "CreateCredentialLibrary(...) got error %v, wanted %v", gErr, tc.err)
|
||||
}
|
||||
return
|
||||
}
|
||||
require.NoError(gErr)
|
||||
if tc.res == nil {
|
||||
require.Nil(got)
|
||||
}
|
||||
if got != nil {
|
||||
assert.Contains(got.GetUri(), tc.res.Uri)
|
||||
assert.True(strings.HasPrefix(got.GetItem().GetId(), tc.idPrefix))
|
||||
gotCreateTime := got.GetItem().GetCreatedTime()
|
||||
gotUpdateTime := got.GetItem().GetUpdatedTime()
|
||||
|
||||
// Verify it is a credential store created after the test setup's default credential store
|
||||
assert.True(gotCreateTime.AsTime().After(defaultCreated.AsTime()), "New credential store should have been created after default credential store. Was created %v, which is after %v", gotCreateTime, defaultCreated)
|
||||
assert.True(gotUpdateTime.AsTime().After(defaultCreated.AsTime()), "New credential store should have been updated after default credential store. Was updated %v, which is after %v", gotUpdateTime, defaultCreated)
|
||||
|
||||
// Clear all values which are hard to compare against.
|
||||
got.Uri, tc.res.Uri = "", ""
|
||||
got.Item.Id, tc.res.Item.Id = "", ""
|
||||
got.Item.CreatedTime, got.Item.UpdatedTime, tc.res.Item.CreatedTime, tc.res.Item.UpdatedTime = nil, nil, nil, nil
|
||||
}
|
||||
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform(), protocmp.SortRepeatedFields(got)), "CreateCredentialLibrary(%q) got response %q, wanted %q", tc.req, got, tc.res)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGet(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
sche := scheduler.TestScheduler(t, conn, wrapper)
|
||||
rw := db.New(conn)
|
||||
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iamRepo, nil
|
||||
}
|
||||
repoFn := func() (*vault.Repository, error) {
|
||||
return vault.NewRepository(rw, rw, kms, sche)
|
||||
}
|
||||
|
||||
_, prj := iam.TestScopes(t, iamRepo)
|
||||
|
||||
store := vault.TestCredentialStores(t, conn, wrapper, prj.GetPublicId(), 1)[0]
|
||||
vl := vault.TestCredentialLibraries(t, conn, wrapper, store.GetPublicId(), 1)[0]
|
||||
s, err := NewService(repoFn, iamRepoFn)
|
||||
require.NoError(t, err)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
id string
|
||||
res *pbs.GetCredentialLibraryResponse
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "success",
|
||||
id: vl.GetPublicId(),
|
||||
res: &pbs.GetCredentialLibraryResponse{
|
||||
Item: &pb.CredentialLibrary{
|
||||
Id: vl.GetPublicId(),
|
||||
CredentialStoreId: vl.GetStoreId(),
|
||||
Scope: &scopepb.ScopeInfo{Id: store.GetScopeId(), Type: scope.Project.String(), ParentScopeId: prj.GetParentId()},
|
||||
Type: credential.VaultSubtype.String(),
|
||||
AuthorizedActions: testAuthorizedActions,
|
||||
CreatedTime: vl.CreateTime.GetTimestamp(),
|
||||
UpdatedTime: vl.UpdateTime.GetTimestamp(),
|
||||
Version: 1,
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String(vl.GetVaultPath()),
|
||||
HttpMethod: wrapperspb.String(vl.GetHttpMethod()),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "not found error",
|
||||
id: fmt.Sprintf("%s_1234567890", vault.CredentialLibraryPrefix),
|
||||
err: handlers.NotFoundError(),
|
||||
},
|
||||
{
|
||||
name: "bad prefix",
|
||||
id: fmt.Sprintf("%s_1234567890", static.HostPrefix),
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := &pbs.GetCredentialLibraryRequest{Id: tc.id}
|
||||
// Test non-anonymous get
|
||||
got, gErr := s.GetCredentialLibrary(auth.DisabledAuthTestContext(iamRepoFn, prj.GetPublicId()), req)
|
||||
if tc.err != nil {
|
||||
require.Error(t, gErr)
|
||||
assert.True(t, errors.Is(gErr, tc.err))
|
||||
return
|
||||
}
|
||||
require.NoError(t, gErr)
|
||||
assert.Empty(t, cmp.Diff(got, tc.res, protocmp.Transform()))
|
||||
|
||||
// Test anonymous get
|
||||
got, gErr = s.GetCredentialLibrary(auth.DisabledAuthTestContext(iamRepoFn, prj.GetPublicId(), auth.WithUserId(auth.AnonymousUserId)), req)
|
||||
require.NoError(t, gErr)
|
||||
require.Nil(t, got.Item.CreatedTime)
|
||||
require.Nil(t, got.Item.UpdatedTime)
|
||||
require.Zero(t, got.Item.Version)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDelete(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
sche := scheduler.TestScheduler(t, conn, wrapper)
|
||||
rw := db.New(conn)
|
||||
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iamRepo, nil
|
||||
}
|
||||
repoFn := func() (*vault.Repository, error) {
|
||||
return vault.NewRepository(rw, rw, kms, sche)
|
||||
}
|
||||
|
||||
_, prj := iam.TestScopes(t, iamRepo)
|
||||
|
||||
store := vault.TestCredentialStores(t, conn, wrapper, prj.GetPublicId(), 1)[0]
|
||||
vl := vault.TestCredentialLibraries(t, conn, wrapper, store.GetPublicId(), 1)[0]
|
||||
s, err := NewService(repoFn, iamRepoFn)
|
||||
require.NoError(t, err)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
id string
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "success",
|
||||
id: vl.GetPublicId(),
|
||||
},
|
||||
{
|
||||
name: "not found error",
|
||||
id: fmt.Sprintf("%s_1234567890", vault.CredentialLibraryPrefix),
|
||||
err: handlers.NotFoundError(),
|
||||
},
|
||||
{
|
||||
name: "bad prefix",
|
||||
id: fmt.Sprintf("%s_1234567890", static.HostPrefix),
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, gErr := s.DeleteCredentialLibrary(auth.DisabledAuthTestContext(iamRepoFn, prj.GetPublicId()), &pbs.DeleteCredentialLibraryRequest{Id: tc.id})
|
||||
assert.Nil(t, got)
|
||||
if tc.err != nil {
|
||||
require.Error(t, gErr)
|
||||
assert.True(t, errors.Is(gErr, tc.err))
|
||||
return
|
||||
}
|
||||
require.NoError(t, gErr)
|
||||
g, err := s.GetCredentialLibrary(auth.DisabledAuthTestContext(iamRepoFn, prj.GetPublicId()), &pbs.GetCredentialLibraryRequest{Id: tc.id})
|
||||
assert.Nil(t, g)
|
||||
assert.True(t, errors.Is(err, handlers.NotFoundError()))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdate(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
sche := scheduler.TestScheduler(t, conn, wrapper)
|
||||
rw := db.New(conn)
|
||||
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iamRepo, nil
|
||||
}
|
||||
repoFn := func() (*vault.Repository, error) {
|
||||
return vault.NewRepository(rw, rw, kms, sche)
|
||||
}
|
||||
|
||||
_, prj := iam.TestScopes(t, iamRepo)
|
||||
ctx := auth.DisabledAuthTestContext(iamRepoFn, prj.GetPublicId())
|
||||
|
||||
s, err := NewService(repoFn, iamRepoFn)
|
||||
require.NoError(t, err)
|
||||
cs := vault.TestCredentialStores(t, conn, wrapper, prj.GetPublicId(), 2)
|
||||
store, diffStore := cs[0], cs[1]
|
||||
|
||||
freshLibrary := func() (*vault.CredentialLibrary, func()) {
|
||||
vl := vault.TestCredentialLibraries(t, conn, wrapper, store.GetPublicId(), 1)[0]
|
||||
clean := func() {
|
||||
_, err := s.DeleteCredentialLibrary(ctx, &pbs.DeleteCredentialLibraryRequest{Id: vl.GetPublicId()})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
return vl, clean
|
||||
}
|
||||
|
||||
fieldmask := func(paths ...string) *fieldmaskpb.FieldMask {
|
||||
return &fieldmaskpb.FieldMask{Paths: paths}
|
||||
}
|
||||
|
||||
v := vault.NewTestVaultServer(t, vault.WithTestVaultTLS(vault.TestClientTLS))
|
||||
_, token := v.CreateToken(t)
|
||||
_ = token
|
||||
|
||||
successCases := []struct {
|
||||
name string
|
||||
req *pbs.UpdateCredentialLibraryRequest
|
||||
res func(*pb.CredentialLibrary) *pb.CredentialLibrary
|
||||
}{
|
||||
{
|
||||
name: "name and description",
|
||||
req: &pbs.UpdateCredentialLibraryRequest{
|
||||
UpdateMask: fieldmask("name", "description"),
|
||||
Item: &pb.CredentialLibrary{
|
||||
Name: wrapperspb.String("basic"),
|
||||
Description: wrapperspb.String("basic"),
|
||||
},
|
||||
},
|
||||
res: func(in *pb.CredentialLibrary) *pb.CredentialLibrary {
|
||||
out := proto.Clone(in).(*pb.CredentialLibrary)
|
||||
out.Name = wrapperspb.String("basic")
|
||||
out.Description = wrapperspb.String("basic")
|
||||
return out
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "update method",
|
||||
req: &pbs.UpdateCredentialLibraryRequest{
|
||||
UpdateMask: fieldmask(httpMethodField),
|
||||
Item: &pb.CredentialLibrary{
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
HttpMethod: wrapperspb.String("pOsT"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
},
|
||||
},
|
||||
res: func(in *pb.CredentialLibrary) *pb.CredentialLibrary {
|
||||
out := proto.Clone(in).(*pb.CredentialLibrary)
|
||||
out.Attributes.Fields["path"] = structpb.NewStringValue("vault/path0")
|
||||
out.Attributes.Fields["http_method"] = structpb.NewStringValue("POST")
|
||||
return out
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "update request body and method",
|
||||
req: &pbs.UpdateCredentialLibraryRequest{
|
||||
UpdateMask: fieldmask(httpRequestBodyField, httpMethodField),
|
||||
Item: &pb.CredentialLibrary{
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
HttpMethod: wrapperspb.String("pOsT"),
|
||||
HttpRequestBody: wrapperspb.String("body"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
},
|
||||
},
|
||||
res: func(in *pb.CredentialLibrary) *pb.CredentialLibrary {
|
||||
out := proto.Clone(in).(*pb.CredentialLibrary)
|
||||
out.Attributes.Fields["path"] = structpb.NewStringValue("vault/path0")
|
||||
out.Attributes.Fields["http_method"] = structpb.NewStringValue("POST")
|
||||
out.Attributes.Fields["http_request_body"] = structpb.NewStringValue("body")
|
||||
return out
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "update path",
|
||||
req: &pbs.UpdateCredentialLibraryRequest{
|
||||
UpdateMask: fieldmask(vaultPathField),
|
||||
Item: &pb.CredentialLibrary{
|
||||
Attributes: func() *structpb.Struct {
|
||||
attrs, err := handlers.ProtoToStruct(&pb.VaultCredentialLibraryAttributes{
|
||||
Path: wrapperspb.String("something"),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return attrs
|
||||
}(),
|
||||
},
|
||||
},
|
||||
res: func(in *pb.CredentialLibrary) *pb.CredentialLibrary {
|
||||
out := proto.Clone(in).(*pb.CredentialLibrary)
|
||||
out.Attributes.Fields["path"] = structpb.NewStringValue("something")
|
||||
return out
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range successCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
st, cleanup := freshLibrary()
|
||||
defer cleanup()
|
||||
|
||||
if tc.req.Item.GetVersion() == 0 {
|
||||
tc.req.Item.Version = 1
|
||||
}
|
||||
if tc.req.GetId() == "" {
|
||||
tc.req.Id = st.GetPublicId()
|
||||
}
|
||||
resToChange, err := s.GetCredentialLibrary(ctx, &pbs.GetCredentialLibraryRequest{Id: st.GetPublicId()})
|
||||
require.NoError(err)
|
||||
want := &pbs.UpdateCredentialLibraryResponse{Item: tc.res(resToChange.GetItem())}
|
||||
|
||||
got, gErr := s.UpdateCredentialLibrary(ctx, tc.req)
|
||||
require.NoError(gErr)
|
||||
require.NotNil(got)
|
||||
|
||||
gotUpdateTime := got.GetItem().GetUpdatedTime()
|
||||
created := st.GetCreateTime().GetTimestamp()
|
||||
assert.True(gotUpdateTime.AsTime().After(created.AsTime()), "Should have been updated after it's creation. Was updated %v, which is after %v", gotUpdateTime, created)
|
||||
|
||||
want.Item.UpdatedTime = got.Item.UpdatedTime
|
||||
|
||||
assert.EqualValues(2, got.Item.Version)
|
||||
want.Item.Version = 2
|
||||
|
||||
assert.Empty(cmp.Diff(got, want, protocmp.Transform()))
|
||||
})
|
||||
}
|
||||
|
||||
vl, cleanup := freshLibrary()
|
||||
defer cleanup()
|
||||
|
||||
errCases := []struct {
|
||||
name string
|
||||
path string
|
||||
item *pb.CredentialLibrary
|
||||
}{
|
||||
{
|
||||
name: "read only type",
|
||||
path: "type",
|
||||
item: &pb.CredentialLibrary{Type: "something"},
|
||||
},
|
||||
{
|
||||
name: "read only store_id",
|
||||
path: "store_id",
|
||||
item: &pb.CredentialLibrary{CredentialStoreId: diffStore.GetPublicId()},
|
||||
},
|
||||
{
|
||||
name: "read only updated_time",
|
||||
path: "updated_time",
|
||||
item: &pb.CredentialLibrary{UpdatedTime: timestamppb.Now()},
|
||||
},
|
||||
{
|
||||
name: "read only created_time",
|
||||
path: "created_time",
|
||||
item: &pb.CredentialLibrary{UpdatedTime: timestamppb.Now()},
|
||||
},
|
||||
{
|
||||
name: "read only authorized actions",
|
||||
path: "authorized actions",
|
||||
item: &pb.CredentialLibrary{AuthorizedActions: append(testAuthorizedActions, "another")},
|
||||
},
|
||||
}
|
||||
for _, tc := range errCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := &pbs.UpdateCredentialLibraryRequest{
|
||||
Id: vl.GetPublicId(),
|
||||
Item: tc.item,
|
||||
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{tc.path}},
|
||||
}
|
||||
req.Item.Version = vl.Version
|
||||
|
||||
got, gErr := s.UpdateCredentialLibrary(ctx, req)
|
||||
assert.Error(t, gErr)
|
||||
assert.Truef(t, errors.Is(gErr, handlers.ApiErrorWithCode(codes.InvalidArgument)), "got error %v, wanted invalid argument", gErr)
|
||||
assert.Nil(t, got)
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("request body and method interactions", func(t *testing.T) {
|
||||
vl, cleanup := freshLibrary()
|
||||
defer cleanup()
|
||||
require.Equal(t, "GET", vl.GetHttpMethod())
|
||||
|
||||
// Cannot set request body on GET request
|
||||
cl, err := s.UpdateCredentialLibrary(ctx, &pbs.UpdateCredentialLibraryRequest{
|
||||
Id: vl.GetPublicId(),
|
||||
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{httpRequestBodyField}},
|
||||
Item: &pb.CredentialLibrary{
|
||||
Version: vl.GetVersion(),
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"http_request_body": structpb.NewStringValue("body"),
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.Error(t, err)
|
||||
require.Nil(t, cl)
|
||||
|
||||
// Can set POST when there is no request body
|
||||
cl, err = s.UpdateCredentialLibrary(ctx, &pbs.UpdateCredentialLibraryRequest{
|
||||
Id: vl.GetPublicId(),
|
||||
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{httpMethodField}},
|
||||
Item: &pb.CredentialLibrary{
|
||||
Version: vl.GetVersion(),
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"http_method": structpb.NewStringValue("POST"),
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, cl)
|
||||
require.Equal(t, "POST", cl.GetItem().GetAttributes().GetFields()["http_method"].GetStringValue())
|
||||
|
||||
// Can set request body on POST
|
||||
cl, err = s.UpdateCredentialLibrary(ctx, &pbs.UpdateCredentialLibraryRequest{
|
||||
Id: vl.GetPublicId(),
|
||||
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{httpRequestBodyField}},
|
||||
Item: &pb.CredentialLibrary{
|
||||
Version: cl.Item.GetVersion(),
|
||||
Attributes: &structpb.Struct{
|
||||
Fields: map[string]*structpb.Value{
|
||||
"http_request_body": structpb.NewStringValue("body"),
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, cl)
|
||||
require.Equal(t, "POST", cl.GetItem().GetAttributes().GetFields()["http_method"].GetStringValue())
|
||||
require.Equal(t, "body", cl.GetItem().GetAttributes().GetFields()["http_request_body"].GetStringValue())
|
||||
|
||||
// Cannot unset POST method (defaulting to GET) when request body is set
|
||||
_, err = s.UpdateCredentialLibrary(ctx, &pbs.UpdateCredentialLibraryRequest{
|
||||
Id: vl.GetPublicId(),
|
||||
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{httpMethodField}},
|
||||
Item: &pb.CredentialLibrary{
|
||||
Version: cl.GetItem().GetVersion(),
|
||||
},
|
||||
})
|
||||
require.Error(t, err)
|
||||
|
||||
// Can clear request body and method (defaulting to GET) in the same request
|
||||
cl, err = s.UpdateCredentialLibrary(ctx, &pbs.UpdateCredentialLibraryRequest{
|
||||
Id: vl.GetPublicId(),
|
||||
UpdateMask: &fieldmaskpb.FieldMask{Paths: []string{httpMethodField, httpRequestBodyField}},
|
||||
Item: &pb.CredentialLibrary{
|
||||
Version: cl.GetItem().GetVersion(),
|
||||
},
|
||||
})
|
||||
assert.NoError(t, err)
|
||||
require.NotNil(t, cl)
|
||||
assert.Equal(t, "GET", cl.GetItem().GetAttributes().GetFields()["http_method"].GetStringValue())
|
||||
assert.Nil(t, cl.GetItem().GetAttributes().GetFields()["http_request_body"])
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,712 @@
|
||||
package credentialstores
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/boundary/globals"
|
||||
"github.com/hashicorp/boundary/internal/auth"
|
||||
"github.com/hashicorp/boundary/internal/credential"
|
||||
"github.com/hashicorp/boundary/internal/credential/vault"
|
||||
"github.com/hashicorp/boundary/internal/credential/vault/store"
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/credentialstores"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/boundary/internal/perms"
|
||||
"github.com/hashicorp/boundary/internal/requests"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/common"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/common/scopeids"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/credentiallibraries"
|
||||
"github.com/hashicorp/boundary/internal/types/action"
|
||||
"github.com/hashicorp/boundary/internal/types/resource"
|
||||
"github.com/hashicorp/boundary/internal/types/scope"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/protobuf/types/known/wrapperspb"
|
||||
)
|
||||
|
||||
const (
|
||||
addressField = "attributes.address"
|
||||
vaultTokenField = "attributes.token"
|
||||
vaultTokenHmacField = "attributes.token_hmac"
|
||||
caCertsField = "attributes.ca_cert"
|
||||
clientCertField = "attributes.client_certificate"
|
||||
clientCertKeyField = "attributes.certificate_key"
|
||||
)
|
||||
|
||||
var (
|
||||
maskManager handlers.MaskManager
|
||||
|
||||
// IdActions contains the set of actions that can be performed on
|
||||
// individual resources
|
||||
IdActions = action.ActionSet{
|
||||
action.NoOp,
|
||||
action.Read,
|
||||
action.Update,
|
||||
action.Delete,
|
||||
}
|
||||
|
||||
// CollectionActions contains the set of actions that can be performed on
|
||||
// this collection
|
||||
CollectionActions = action.ActionSet{
|
||||
action.Create,
|
||||
action.List,
|
||||
}
|
||||
|
||||
collectionTypeMap = map[resource.Type]action.ActionSet{
|
||||
resource.CredentialLibrary: credentiallibraries.CollectionActions,
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if maskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&store.CredentialStore{}, &store.Token{}, &store.ClientCertificate{}},
|
||||
handlers.MaskSource{&pb.CredentialStore{}, &pb.VaultCredentialStoreAttributes{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Service handles request as described by the pbs.CredentialStoreServiceServer interface.
|
||||
type Service struct {
|
||||
pbs.UnimplementedCredentialStoreServiceServer
|
||||
|
||||
iamRepoFn common.IamRepoFactory
|
||||
repoFn common.VaultCredentialRepoFactory
|
||||
}
|
||||
|
||||
// NewService returns a credential store service which handles credential store related requests to boundary.
|
||||
func NewService(repo common.VaultCredentialRepoFactory, iamRepo common.IamRepoFactory) (Service, error) {
|
||||
const op = "credentialstores.NewService"
|
||||
if iamRepo == nil {
|
||||
return Service{}, errors.New(errors.InvalidParameter, op, "missing iam repository")
|
||||
}
|
||||
if repo == nil {
|
||||
return Service{}, errors.New(errors.InvalidParameter, op, "missing vault credential repository")
|
||||
}
|
||||
return Service{iamRepoFn: iamRepo, repoFn: repo}, nil
|
||||
}
|
||||
|
||||
var _ pbs.CredentialStoreServiceServer = Service{}
|
||||
|
||||
// ListCredentialStores implements the interface pbs.CredentialStoreServiceServer
|
||||
func (s Service) ListCredentialStores(ctx context.Context, req *pbs.ListCredentialStoresRequest) (*pbs.ListCredentialStoresResponse, error) {
|
||||
if err := validateListRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetScopeId(), action.List)
|
||||
if authResults.Error != nil {
|
||||
// If it's forbidden, and it's a recursive request, and they're
|
||||
// successfully authenticated but just not authorized, keep going as we
|
||||
// may have authorization on downstream scopes.
|
||||
if authResults.Error == handlers.ForbiddenError() &&
|
||||
req.GetRecursive() &&
|
||||
authResults.AuthenticationFinished {
|
||||
} else {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
}
|
||||
|
||||
scopeIds, scopeInfoMap, err := scopeids.GetListingScopeIds(
|
||||
ctx, s.iamRepoFn, authResults, req.GetScopeId(), resource.CredentialStore, req.GetRecursive(), false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// If no scopes match, return an empty response
|
||||
if len(scopeIds) == 0 {
|
||||
return &pbs.ListCredentialStoresResponse{}, nil
|
||||
}
|
||||
|
||||
csl, err := s.listFromRepo(ctx, scopeIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(csl) == 0 {
|
||||
return &pbs.ListCredentialStoresResponse{}, nil
|
||||
}
|
||||
|
||||
filter, err := handlers.NewFilter(req.GetFilter())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
finalItems := make([]*pb.CredentialStore, 0, len(csl))
|
||||
res := perms.Resource{
|
||||
Type: resource.CredentialStore,
|
||||
}
|
||||
for _, item := range csl {
|
||||
res.Id = item.GetPublicId()
|
||||
res.ScopeId = item.GetScopeId()
|
||||
authorizedActions := authResults.FetchActionSetForId(ctx, item.GetPublicId(), IdActions, auth.WithResource(&res)).Strings()
|
||||
if len(authorizedActions) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
outputFields := authResults.FetchOutputFields(res, action.List).SelfOrDefaults(authResults.UserId)
|
||||
outputOpts := make([]handlers.Option, 0, 3)
|
||||
outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields))
|
||||
if outputFields.Has(globals.ScopeField) {
|
||||
outputOpts = append(outputOpts, handlers.WithScope(scopeInfoMap[item.GetScopeId()]))
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedActionsField) {
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authorizedActions))
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedCollectionActionsField) {
|
||||
collectionActions, err := auth.CalculateAuthorizedCollectionActions(ctx, authResults, collectionTypeMap, authResults.Scope.Id, item.GetPublicId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedCollectionActions(collectionActions))
|
||||
}
|
||||
|
||||
item, err := toProto(item, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if filter.Match(item) {
|
||||
finalItems = append(finalItems, item)
|
||||
}
|
||||
}
|
||||
return &pbs.ListCredentialStoresResponse{Items: finalItems}, nil
|
||||
}
|
||||
|
||||
// GetCredentialStore implements the interface pbs.CredentialStoreServiceServer.
|
||||
func (s Service) GetCredentialStore(ctx context.Context, req *pbs.GetCredentialStoreRequest) (*pbs.GetCredentialStoreResponse, error) {
|
||||
const op = "credentialstores.(Service).GetCredentialStore"
|
||||
|
||||
if err := validateGetRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetId(), action.Read)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
cs, err := s.getFromRepo(ctx, req.GetId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputFields, ok := requests.OutputFields(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New(errors.Internal, op, "no request context found")
|
||||
}
|
||||
|
||||
outputOpts := make([]handlers.Option, 0, 3)
|
||||
outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields))
|
||||
if outputFields.Has(globals.ScopeField) {
|
||||
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedActionsField) {
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, cs.GetPublicId(), IdActions).Strings()))
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedCollectionActionsField) {
|
||||
collectionActions, err := auth.CalculateAuthorizedCollectionActions(ctx, authResults, collectionTypeMap, authResults.Scope.Id, cs.GetPublicId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedCollectionActions(collectionActions))
|
||||
}
|
||||
|
||||
item, err := toProto(cs, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &pbs.GetCredentialStoreResponse{Item: item}, nil
|
||||
}
|
||||
|
||||
// CreateCredentialStore implements the interface pbs.CredentialStoreServiceServer.
|
||||
func (s Service) CreateCredentialStore(ctx context.Context, req *pbs.CreateCredentialStoreRequest) (*pbs.CreateCredentialStoreResponse, error) {
|
||||
const op = "credentialstores.(Service).CreateCredentialStore"
|
||||
|
||||
if err := validateCreateRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetItem().GetScopeId(), action.Create)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
cs, err := s.createInRepo(ctx, authResults.Scope.GetId(), req.GetItem())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputFields, ok := requests.OutputFields(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New(errors.Internal, op, "no request context found")
|
||||
}
|
||||
|
||||
outputOpts := make([]handlers.Option, 0, 3)
|
||||
outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields))
|
||||
if outputFields.Has(globals.ScopeField) {
|
||||
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedActionsField) {
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, cs.GetPublicId(), IdActions).Strings()))
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedCollectionActionsField) {
|
||||
collectionActions, err := auth.CalculateAuthorizedCollectionActions(ctx, authResults, collectionTypeMap, authResults.Scope.Id, cs.GetPublicId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedCollectionActions(collectionActions))
|
||||
}
|
||||
|
||||
item, err := toProto(cs, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &pbs.CreateCredentialStoreResponse{
|
||||
Item: item,
|
||||
Uri: fmt.Sprintf("credential-stores/%s", item.GetId()),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// UpdateCredentialStore implements the interface pbs.CredentialStoreServiceServer.
|
||||
func (s Service) UpdateCredentialStore(ctx context.Context, req *pbs.UpdateCredentialStoreRequest) (*pbs.UpdateCredentialStoreResponse, error) {
|
||||
const op = "credentialstores.(Service).UpdateCredentialStore"
|
||||
|
||||
if err := validateUpdateRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetId(), action.Update)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
cs, err := s.updateInRepo(ctx, authResults.Scope.GetId(), req.GetId(), req.GetUpdateMask().GetPaths(), req.GetItem())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputFields, ok := requests.OutputFields(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New(errors.Internal, op, "no request context found")
|
||||
}
|
||||
|
||||
outputOpts := make([]handlers.Option, 0, 3)
|
||||
outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields))
|
||||
if outputFields.Has(globals.ScopeField) {
|
||||
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedActionsField) {
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, cs.GetPublicId(), IdActions).Strings()))
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedCollectionActionsField) {
|
||||
collectionActions, err := auth.CalculateAuthorizedCollectionActions(ctx, authResults, collectionTypeMap, authResults.Scope.Id, cs.GetPublicId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedCollectionActions(collectionActions))
|
||||
}
|
||||
|
||||
item, err := toProto(cs, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &pbs.UpdateCredentialStoreResponse{Item: item}, nil
|
||||
}
|
||||
|
||||
// DeleteCredentialStore implements the interface pbs.CredentialStoreServiceServer.
|
||||
func (s Service) DeleteCredentialStore(ctx context.Context, req *pbs.DeleteCredentialStoreRequest) (*pbs.DeleteCredentialStoreResponse, error) {
|
||||
if err := validateDeleteRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetId(), action.Delete)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
_, err := s.deleteFromRepo(ctx, req.GetId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s Service) listFromRepo(ctx context.Context, scopeIds []string) ([]*vault.CredentialStore, error) {
|
||||
const op = "credentialstores.(Service).listFromRepo"
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
csl, err := repo.ListCredentialStores(ctx, scopeIds)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
return csl, nil
|
||||
}
|
||||
|
||||
func (s Service) getFromRepo(ctx context.Context, id string) (credential.Store, error) {
|
||||
const op = "credentialstores.(Service).getFromRepo"
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
cs, err := repo.LookupCredentialStore(ctx, id)
|
||||
if err != nil && !errors.IsNotFoundError(err) {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
if cs == nil {
|
||||
return nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("credential store %q not found", id))
|
||||
}
|
||||
return cs, err
|
||||
}
|
||||
|
||||
func (s Service) createInRepo(ctx context.Context, projId string, item *pb.CredentialStore) (credential.Store, error) {
|
||||
const op = "credentialstores.(Service).createInRepo"
|
||||
cs, err := toStorageVaultStore(projId, item)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
out, err := repo.CreateCredentialStore(ctx, cs)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op, errors.WithMsg("unable to create credential store"))
|
||||
}
|
||||
if out == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create credential store but no error returned from repository.")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s Service) updateInRepo(ctx context.Context, projId, id string, mask []string, item *pb.CredentialStore) (credential.Store, error) {
|
||||
const op = "credentialstores.(Service).updateInRepo"
|
||||
cs, err := toStorageVaultStore(projId, item)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
cs.PublicId = id
|
||||
|
||||
dbMask := maskManager.Translate(mask)
|
||||
if len(dbMask) == 0 {
|
||||
return nil, handlers.InvalidArgumentErrorf("No valid fields included in the update mask.", map[string]string{"update_mask": "No valid fields provided in the update mask."})
|
||||
}
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
out, rowsUpdated, err := repo.UpdateCredentialStore(ctx, cs, item.GetVersion(), dbMask)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op, errors.WithMsg("unable to update credential store"))
|
||||
}
|
||||
if rowsUpdated == 0 {
|
||||
return nil, handlers.NotFoundErrorf("Credential Store %q doesn't exist or incorrect version provided.", id)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (s Service) deleteFromRepo(ctx context.Context, id string) (bool, error) {
|
||||
const op = "credentialstores.(Service).deleteFromRepo"
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
rows, err := repo.DeleteCredentialStore(ctx, id)
|
||||
if err != nil {
|
||||
if errors.IsNotFoundError(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, errors.Wrap(err, op, errors.WithMsg("unable to delete credential store"))
|
||||
}
|
||||
return rows > 0, nil
|
||||
}
|
||||
|
||||
func (s Service) authResult(ctx context.Context, id string, a action.Type) auth.VerifyResults {
|
||||
res := auth.VerifyResults{}
|
||||
iamRepo, err := s.iamRepoFn()
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return res
|
||||
}
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return res
|
||||
}
|
||||
|
||||
var parentId string
|
||||
opts := []auth.Option{auth.WithType(resource.CredentialStore), auth.WithAction(a)}
|
||||
switch a {
|
||||
case action.List, action.Create:
|
||||
parentId = id
|
||||
scp, err := iamRepo.LookupScope(ctx, parentId)
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return res
|
||||
}
|
||||
if scp == nil {
|
||||
res.Error = handlers.NotFoundError()
|
||||
return res
|
||||
}
|
||||
default:
|
||||
cs, err := repo.LookupCredentialStore(ctx, id)
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return res
|
||||
}
|
||||
if cs == nil {
|
||||
res.Error = handlers.NotFoundError()
|
||||
return res
|
||||
}
|
||||
parentId = cs.GetScopeId()
|
||||
opts = append(opts, auth.WithId(id))
|
||||
}
|
||||
opts = append(opts, auth.WithScopeId(parentId))
|
||||
return auth.Verify(ctx, opts...)
|
||||
}
|
||||
|
||||
func toProto(in credential.Store, opt ...handlers.Option) (*pb.CredentialStore, error) {
|
||||
const op = "credentialstores.toProto"
|
||||
|
||||
opts := handlers.GetOpts(opt...)
|
||||
if opts.WithOutputFields == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "output fields not found when building credential store proto")
|
||||
}
|
||||
outputFields := *opts.WithOutputFields
|
||||
|
||||
out := pb.CredentialStore{}
|
||||
if outputFields.Has(globals.IdField) {
|
||||
out.Id = in.GetPublicId()
|
||||
}
|
||||
if outputFields.Has(globals.ScopeIdField) {
|
||||
out.ScopeId = in.GetScopeId()
|
||||
}
|
||||
if outputFields.Has(globals.TypeField) {
|
||||
out.Type = credential.SubtypeFromId(in.GetPublicId()).String()
|
||||
}
|
||||
if outputFields.Has(globals.DescriptionField) && in.GetDescription() != "" {
|
||||
out.Description = wrapperspb.String(in.GetDescription())
|
||||
}
|
||||
if outputFields.Has(globals.NameField) && in.GetName() != "" {
|
||||
out.Name = wrapperspb.String(in.GetName())
|
||||
}
|
||||
if outputFields.Has(globals.CreatedTimeField) {
|
||||
out.CreatedTime = in.GetCreateTime().GetTimestamp()
|
||||
}
|
||||
if outputFields.Has(globals.UpdatedTimeField) {
|
||||
out.UpdatedTime = in.GetUpdateTime().GetTimestamp()
|
||||
}
|
||||
if outputFields.Has(globals.VersionField) {
|
||||
out.Version = in.GetVersion()
|
||||
}
|
||||
if outputFields.Has(globals.ScopeField) {
|
||||
out.Scope = opts.WithScope
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedActionsField) {
|
||||
out.AuthorizedActions = opts.WithAuthorizedActions
|
||||
}
|
||||
if outputFields.Has(globals.AttributesField) {
|
||||
switch credential.SubtypeFromId(in.GetPublicId()) {
|
||||
case credential.VaultSubtype:
|
||||
vaultIn, ok := in.(*vault.CredentialStore)
|
||||
if !ok {
|
||||
return nil, errors.New(errors.Internal, op, "unable to cast to vault credential store")
|
||||
}
|
||||
attrs := &pb.VaultCredentialStoreAttributes{
|
||||
Address: wrapperspb.String(vaultIn.GetVaultAddress()),
|
||||
}
|
||||
if vaultIn.GetNamespace() != "" {
|
||||
attrs.Namespace = wrapperspb.String(vaultIn.GetNamespace())
|
||||
}
|
||||
if len(vaultIn.GetCaCert()) != 0 {
|
||||
attrs.CaCert = wrapperspb.String(string(vaultIn.GetCaCert()))
|
||||
}
|
||||
if vaultIn.GetTlsServerName() != "" {
|
||||
attrs.TlsServerName = wrapperspb.String(vaultIn.GetTlsServerName())
|
||||
}
|
||||
if vaultIn.GetTlsSkipVerify() {
|
||||
attrs.TlsSkipVerify = wrapperspb.Bool(vaultIn.GetTlsSkipVerify())
|
||||
}
|
||||
if vaultIn.Token() != nil {
|
||||
attrs.TokenHmac = base64.RawURLEncoding.EncodeToString(vaultIn.Token().GetTokenHmac())
|
||||
}
|
||||
if cc := vaultIn.ClientCertificate(); cc != nil {
|
||||
if len(cc.GetCertificate()) != 0 {
|
||||
attrs.ClientCertificate = wrapperspb.String(string(cc.GetCertificate()))
|
||||
}
|
||||
attrs.ClientCertificateKeyHmac = base64.RawURLEncoding.EncodeToString(cc.GetCertificateKeyHmac())
|
||||
}
|
||||
|
||||
var err error
|
||||
if out.Attributes, err = handlers.ProtoToStruct(attrs); err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
}
|
||||
}
|
||||
return &out, nil
|
||||
}
|
||||
|
||||
func toStorageVaultStore(scopeId string, in *pb.CredentialStore) (out *vault.CredentialStore, err error) {
|
||||
const op = "credentialstores.toStorageVaultStore"
|
||||
var opts []vault.Option
|
||||
if in.GetName() != nil {
|
||||
opts = append(opts, vault.WithName(in.GetName().GetValue()))
|
||||
}
|
||||
if in.GetDescription() != nil {
|
||||
opts = append(opts, vault.WithDescription(in.GetDescription().GetValue()))
|
||||
}
|
||||
|
||||
attrs := &pb.VaultCredentialStoreAttributes{}
|
||||
if err := handlers.StructToProto(in.GetAttributes(), attrs); err != nil {
|
||||
return nil, errors.Wrap(err, op, errors.WithMsg("unable to parse the attributes"))
|
||||
}
|
||||
if attrs.GetTlsServerName() != nil {
|
||||
opts = append(opts, vault.WithTlsServerName(attrs.GetTlsServerName().GetValue()))
|
||||
}
|
||||
if attrs.GetTlsSkipVerify().GetValue() {
|
||||
opts = append(opts, vault.WithTlsSkipVerify(attrs.GetTlsSkipVerify().GetValue()))
|
||||
}
|
||||
if attrs.GetNamespace().GetValue() != "" {
|
||||
opts = append(opts, vault.WithNamespace(attrs.GetNamespace().GetValue()))
|
||||
}
|
||||
|
||||
// TODO (ICU-1478 and ICU-1479): Update the vault's interface around ca cert to match oidc's,
|
||||
// accepting x509.Certificate instead of []byte
|
||||
if attrs.GetCaCert() != nil {
|
||||
opts = append(opts, vault.WithCACert([]byte(attrs.GetCaCert().GetValue())))
|
||||
}
|
||||
pemCerts, pemPk, err := extractClientCertAndPk(attrs.GetClientCertificate().GetValue(), attrs.GetClientCertificateKey().GetValue())
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
if len(pemCerts) != 0 {
|
||||
var cert []byte
|
||||
for _, c := range pemCerts {
|
||||
cert = append(cert, pem.EncodeToMemory(c)...)
|
||||
}
|
||||
var pk []byte
|
||||
if pemPk != nil {
|
||||
pk = pem.EncodeToMemory(pemPk)
|
||||
}
|
||||
cc, err := vault.NewClientCertificate(cert, pk)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
opts = append(opts, vault.WithClientCert(cc))
|
||||
}
|
||||
|
||||
cs, err := vault.NewCredentialStore(scopeId, attrs.GetAddress().GetValue(), []byte(attrs.GetToken().GetValue()), opts...)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op, errors.WithMsg("unable to build credential store for creation"))
|
||||
}
|
||||
return cs, err
|
||||
}
|
||||
|
||||
// A validateX method should exist for each method above. These methods do not make calls to any backing service but enforce
|
||||
// requirements on the structure of the request. They verify that:
|
||||
// * The path passed in is correctly formatted
|
||||
// * All required parameters are set
|
||||
// * There are no conflicting parameters provided
|
||||
func validateGetRequest(req *pbs.GetCredentialStoreRequest) error {
|
||||
return handlers.ValidateGetRequest(handlers.NoopValidatorFn, req, vault.CredentialStorePrefix)
|
||||
}
|
||||
|
||||
func validateCreateRequest(req *pbs.CreateCredentialStoreRequest) error {
|
||||
return handlers.ValidateCreateRequest(req.GetItem(), func() map[string]string {
|
||||
badFields := map[string]string{}
|
||||
if !handlers.ValidId(handlers.Id(req.GetItem().GetScopeId()), scope.Project.Prefix()) {
|
||||
badFields["scope_id"] = "This field must be a valid project scope id."
|
||||
}
|
||||
switch credential.SubtypeFromType(req.GetItem().GetType()) {
|
||||
case credential.VaultSubtype:
|
||||
attrs := &pb.VaultCredentialStoreAttributes{}
|
||||
if err := handlers.StructToProto(req.GetItem().GetAttributes(), attrs); err != nil {
|
||||
badFields[globals.AttributesField] = fmt.Sprintf("Attribute fields do not match the expected format. Got %#v", req.GetItem().GetAttributes().AsMap())
|
||||
break
|
||||
}
|
||||
if attrs.GetAddress().GetValue() == "" {
|
||||
badFields[addressField] = "Field required for creating a vault credential store."
|
||||
}
|
||||
if attrs.GetToken().GetValue() == "" {
|
||||
badFields[vaultTokenField] = "Field required for creating a vault credential store."
|
||||
}
|
||||
if attrs.GetTokenHmac() != "" {
|
||||
badFields[vaultTokenHmacField] = "This is a read only field."
|
||||
}
|
||||
|
||||
// TODO(ICU-1478 and ICU-1479): Validate client and CA certificate payloads
|
||||
_, err := decodePemBlocks(attrs.GetCaCert().GetValue())
|
||||
if attrs.GetCaCert() != nil && err != nil {
|
||||
badFields[caCertsField] = "Incorrectly formatted value."
|
||||
}
|
||||
|
||||
cs, pk, err := extractClientCertAndPk(attrs.GetClientCertificate().GetValue(), attrs.GetClientCertificateKey().GetValue())
|
||||
if err != nil {
|
||||
badFields[clientCertField] = fmt.Sprintf("Invalid values: %q", err.Error())
|
||||
}
|
||||
if attrs.GetClientCertificate() == nil && attrs.GetClientCertificateKey() != nil {
|
||||
badFields[clientCertKeyField] = "Cannot set a client certificate private key without the client certificate."
|
||||
}
|
||||
if len(cs) > 0 && pk == nil {
|
||||
badFields[clientCertField] = "Cannot set a client certificate without a private key."
|
||||
}
|
||||
default:
|
||||
badFields[globals.TypeField] = "This is a required field and must be a known credential store type."
|
||||
}
|
||||
return badFields
|
||||
})
|
||||
}
|
||||
|
||||
func validateUpdateRequest(req *pbs.UpdateCredentialStoreRequest) error {
|
||||
return handlers.ValidateUpdateRequest(req, req.GetItem(), func() map[string]string {
|
||||
badFields := map[string]string{}
|
||||
switch credential.SubtypeFromId(req.GetId()) {
|
||||
case credential.VaultSubtype:
|
||||
if req.GetItem().GetType() != "" && credential.SubtypeFromType(req.GetItem().GetType()) != credential.VaultSubtype {
|
||||
badFields["type"] = "Cannot modify resource type."
|
||||
}
|
||||
attrs := &pb.VaultCredentialStoreAttributes{}
|
||||
if err := handlers.StructToProto(req.GetItem().GetAttributes(), attrs); err != nil {
|
||||
badFields[globals.AttributesField] = "Attribute fields do not match the expected format."
|
||||
break
|
||||
}
|
||||
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), addressField) &&
|
||||
attrs.GetAddress().GetValue() == "" {
|
||||
badFields[addressField] = "This is a required field and cannot be unset."
|
||||
}
|
||||
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), vaultTokenField) &&
|
||||
attrs.GetToken().GetValue() == "" {
|
||||
badFields[vaultTokenField] = "This is a required field and cannot be unset."
|
||||
}
|
||||
if attrs.GetTokenHmac() != "" {
|
||||
badFields[vaultTokenHmacField] = "This is a read only field."
|
||||
}
|
||||
|
||||
// TODO(ICU-1478 and ICU-1479): Validate client and CA certificate payloads
|
||||
_, err := decodePemBlocks(attrs.GetCaCert().GetValue())
|
||||
if attrs.GetCaCert() != nil && err != nil {
|
||||
badFields[caCertsField] = "Incorrectly formatted value."
|
||||
}
|
||||
|
||||
_, _, err = extractClientCertAndPk(attrs.GetClientCertificate().GetValue(), attrs.GetClientCertificateKey().GetValue())
|
||||
if err != nil {
|
||||
badFields[clientCertField] = fmt.Sprintf("Invalid values: %q", err.Error())
|
||||
}
|
||||
}
|
||||
return badFields
|
||||
}, vault.CredentialStorePrefix)
|
||||
}
|
||||
|
||||
func validateDeleteRequest(req *pbs.DeleteCredentialStoreRequest) error {
|
||||
return handlers.ValidateDeleteRequest(handlers.NoopValidatorFn, req, vault.CredentialStorePrefix)
|
||||
}
|
||||
|
||||
func validateListRequest(req *pbs.ListCredentialStoresRequest) error {
|
||||
badFields := map[string]string{}
|
||||
if !handlers.ValidId(handlers.Id(req.GetScopeId()), scope.Project.Prefix()) &&
|
||||
!req.GetRecursive() {
|
||||
badFields[globals.ScopeIdField] = "This field must be a valid project scope ID or the list operation must be recursive."
|
||||
}
|
||||
if _, err := handlers.NewFilter(req.GetFilter()); err != nil {
|
||||
badFields["filter"] = fmt.Sprintf("This field could not be parsed. %v", err)
|
||||
}
|
||||
if len(badFields) > 0 {
|
||||
return handlers.InvalidArgumentErrorf("Improperly formatted identifier.", badFields)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+1040
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,70 @@
|
||||
package credentialstores
|
||||
|
||||
import (
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
)
|
||||
|
||||
// extractClientCertAndPk takes the values passed into the api for client
|
||||
// certificate and client certificate key and parses them into pem blocks.
|
||||
// Any non certificate pem blocks are treated as a private key. An error is
|
||||
// returned if there is more than 1 private key provided across both fields.
|
||||
func extractClientCertAndPk(cert, pk string) ([]*pem.Block, *pem.Block, error) {
|
||||
const op = "credentialstores.extractClientCertAndPk"
|
||||
pks, err := decodePemBlocks(pk)
|
||||
if err != nil {
|
||||
return nil, nil, errors.Wrap(err, op, errors.WithMsg("failed to parse client certificate private key"))
|
||||
}
|
||||
var pkPem *pem.Block
|
||||
switch len(pks) {
|
||||
case 0:
|
||||
case 1:
|
||||
pkPem = pks[0]
|
||||
default:
|
||||
return nil, nil, errors.New(errors.InvalidParameter, op, "private key payload contained multiple pem blocks")
|
||||
}
|
||||
|
||||
bs, err := decodePemBlocks(cert)
|
||||
if err != nil {
|
||||
return nil, nil, errors.Wrap(err, op, errors.WithMsg("failed to parse client certificate into pem blocks"))
|
||||
}
|
||||
pkIdx := -1
|
||||
for i, b := range bs {
|
||||
if !strings.Contains(b.Type, "CERTIFICATE") {
|
||||
switch {
|
||||
case pkPem == nil:
|
||||
pkIdx, pkPem = i, b
|
||||
case pkIdx < 0:
|
||||
return nil, nil, errors.New(errors.InvalidParameter, op, "client certificate contains a private key when one was also provided separately")
|
||||
default:
|
||||
return nil, nil, errors.New(errors.InvalidParameter, op, fmt.Sprintf("second primary key found at %d after previous one found at %d", i, pkIdx))
|
||||
}
|
||||
}
|
||||
}
|
||||
if pkIdx >= 0 {
|
||||
bs = append(bs[:pkIdx], bs[pkIdx+1:]...)
|
||||
}
|
||||
return bs, pkPem, nil
|
||||
}
|
||||
|
||||
func decodePemBlocks(input string) ([]*pem.Block, error) {
|
||||
const op = "credentialstores.decodePemBlocks"
|
||||
cpIn := make([]byte, len(input))
|
||||
copy(cpIn, input)
|
||||
var p *pem.Block
|
||||
var ret []*pem.Block
|
||||
for {
|
||||
p, cpIn = pem.Decode(cpIn)
|
||||
if p == nil {
|
||||
break
|
||||
}
|
||||
ret = append(ret, p)
|
||||
}
|
||||
if len(cpIn) > 0 {
|
||||
return nil, errors.New(errors.InvalidParameter, op, "not all data parseable by pem block")
|
||||
}
|
||||
return ret, nil
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package credentialstores
|
||||
|
||||
import (
|
||||
"encoding/pem"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/credential/vault"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestPkAndClientCerts(t *testing.T) {
|
||||
s := vault.NewTestVaultServer(t, vault.WithTestVaultTLS(vault.TestClientTLS))
|
||||
|
||||
t.Run("seperate client cert and key", func(t *testing.T) {
|
||||
c, k, err := extractClientCertAndPk(string(s.ClientCert), string(s.ClientKey))
|
||||
assert.NoError(t, err)
|
||||
require.NotNil(t, k)
|
||||
assert.Equal(t, s.ClientKey, pem.EncodeToMemory(k))
|
||||
require.Len(t, c, 1)
|
||||
assert.Equal(t, s.ClientCert, pem.EncodeToMemory(c[0]))
|
||||
})
|
||||
|
||||
t.Run("client cert and key bundled in cert", func(t *testing.T) {
|
||||
c, k, err := extractClientCertAndPk(string(s.ClientCert)+string(s.ClientKey), "")
|
||||
assert.NoError(t, err)
|
||||
require.NotNil(t, k)
|
||||
assert.Equal(t, s.ClientKey, pem.EncodeToMemory(k))
|
||||
require.Len(t, c, 1)
|
||||
assert.Equal(t, s.ClientCert, pem.EncodeToMemory(c[0]))
|
||||
})
|
||||
|
||||
t.Run("cert with no private key", func(t *testing.T) {
|
||||
c, k, err := extractClientCertAndPk(string(s.ClientCert), "")
|
||||
assert.NoError(t, err)
|
||||
assert.Nil(t, k)
|
||||
require.Len(t, c, 1)
|
||||
assert.Equal(t, s.ClientCert, pem.EncodeToMemory(c[0]))
|
||||
})
|
||||
|
||||
t.Run("private key with no cert", func(t *testing.T) {
|
||||
c, k, err := extractClientCertAndPk("", string(s.ClientKey))
|
||||
assert.NoError(t, err)
|
||||
assert.NotNil(t, k)
|
||||
assert.Equal(t, s.ClientKey, pem.EncodeToMemory(k))
|
||||
require.Empty(t, c)
|
||||
})
|
||||
|
||||
t.Run("error cases", func(t *testing.T) {
|
||||
_, _, err := extractClientCertAndPk(string(s.ClientCert), "invalid key")
|
||||
assert.Error(t, err)
|
||||
_, _, err = extractClientCertAndPk("invalid cert", string(s.ClientKey))
|
||||
assert.Error(t, err)
|
||||
|
||||
// private key with the cert and the private key
|
||||
c, k, err := extractClientCertAndPk(string(s.ClientCert)+string(s.ClientKey), string(s.ClientKey))
|
||||
assert.Error(t, err)
|
||||
assert.Nil(t, k)
|
||||
assert.Empty(t, c)
|
||||
})
|
||||
}
|
||||
@@ -49,7 +49,7 @@ var (
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if maskManager, err = handlers.NewMaskManager(&store.Group{}, &pb.Group{}); err != nil {
|
||||
if maskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&store.Group{}}, handlers.MaskSource{&pb.Group{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ var (
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if maskManager, err = handlers.NewMaskManager(&store.HostCatalog{}, &pb.HostCatalog{}); err != nil {
|
||||
if maskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&store.HostCatalog{}}, handlers.MaskSource{&pb.HostCatalog{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@@ -342,7 +342,7 @@ func (s Service) listFromRepo(ctx context.Context, scopeIds []string) ([]*static
|
||||
}
|
||||
|
||||
func (s Service) createInRepo(ctx context.Context, projId string, item *pb.HostCatalog) (*static.HostCatalog, error) {
|
||||
const op = "host_catalogs.(Servivce).createInRepo"
|
||||
const op = "host_catalogs.(Service).createInRepo"
|
||||
var opts []static.Option
|
||||
if item.GetName() != nil {
|
||||
opts = append(opts, static.WithName(item.GetName().GetValue()))
|
||||
|
||||
@@ -48,7 +48,7 @@ var (
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if maskManager, err = handlers.NewMaskManager(&store.HostSet{}, &pb.HostSet{}); err != nil {
|
||||
if maskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&store.HostSet{}}, handlers.MaskSource{&pb.HostSet{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@@ -172,11 +172,11 @@ func (s Service) CreateHostSet(ctx context.Context, req *pbs.CreateHostSetReques
|
||||
if err := validateCreateRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cat, authResults := s.parentAndAuthResult(ctx, req.GetItem().GetHostCatalogId(), action.Create)
|
||||
_, authResults := s.parentAndAuthResult(ctx, req.GetItem().GetHostCatalogId(), action.Create)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
hs, err := s.createInRepo(ctx, authResults.Scope.GetId(), cat.GetPublicId(), req.GetItem())
|
||||
hs, err := s.createInRepo(ctx, authResults.Scope.GetId(), req.GetItem().GetHostCatalogId(), req.GetItem())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ var (
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if maskManager, err = handlers.NewMaskManager(&store.Host{}, &pb.Host{}, &pb.StaticHostAttributes{}); err != nil {
|
||||
if maskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&store.Host{}}, handlers.MaskSource{&pb.Host{}, &pb.StaticHostAttributes{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ var (
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if oidcMaskManager, err = handlers.NewMaskManager(&oidcstore.ManagedGroup{}, &pb.ManagedGroup{}, &pb.OidcManagedGroupAttributes{}); err != nil {
|
||||
if oidcMaskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&oidcstore.ManagedGroup{}}, handlers.MaskSource{&pb.ManagedGroup{}, &pb.OidcManagedGroupAttributes{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,12 +14,17 @@ import (
|
||||
|
||||
type MaskManager map[string]string
|
||||
|
||||
type (
|
||||
MaskDestination []protoreflect.ProtoMessage
|
||||
MaskSource []protoreflect.ProtoMessage
|
||||
)
|
||||
|
||||
// NewMaskManager returns a mask manager that can translate field masks into the first proto from all subsequent
|
||||
// protos assuming they are both using the mask_mapping custom option. Error is returned if no mappings are
|
||||
// found or if one of the passed protos has a mapping that doesn't reciprocate.
|
||||
func NewMaskManager(dest protoreflect.ProtoMessage, src ...protoreflect.ProtoMessage) (MaskManager, error) {
|
||||
func NewMaskManager(dest MaskDestination, src MaskSource) (MaskManager, error) {
|
||||
const op = "handlers.NewMaskManager"
|
||||
srcToDest, err := mapFromProto(src...)
|
||||
srcToDest, err := mapFromProto(src)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -51,7 +56,7 @@ func NewMaskManager(dest protoreflect.ProtoMessage, src ...protoreflect.ProtoMes
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func mapFromProto(ps ...protoreflect.ProtoMessage) (map[string]string, error) {
|
||||
func mapFromProto(ps []protoreflect.ProtoMessage) (map[string]string, error) {
|
||||
const op = "handlers.mapFromProto"
|
||||
mapping := make(map[string]string)
|
||||
for _, p := range ps {
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
)
|
||||
|
||||
func TestMaskManager(t *testing.T) {
|
||||
mm, err := NewMaskManager(&pb.TestProperlyNamedFields{}, &pb.TestBase{})
|
||||
mm, err := NewMaskManager(MaskDestination{&pb.TestProperlyNamedFields{}}, MaskSource{&pb.TestBase{}})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string(nil), mm.Translate([]string{"doesnt_exist"}))
|
||||
assert.Equal(t, []string{"OtherFirstField"}, mm.Translate([]string{"first_field"}))
|
||||
@@ -20,7 +20,7 @@ func TestMaskManager(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestMaskManager_Split(t *testing.T) {
|
||||
mm, err := NewMaskManager(&pb.TestProperlyNamedFields{}, &pb.TestBaseSplit1{}, &pb.TestBaseSplit2{})
|
||||
mm, err := NewMaskManager(MaskDestination{&pb.TestProperlyNamedFields{}}, MaskSource{&pb.TestBaseSplit1{}, &pb.TestBaseSplit2{}})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string(nil), mm.Translate([]string{"doesnt_exist"}))
|
||||
assert.Equal(t, []string{"OtherFirstField"}, mm.Translate([]string{"first_field"}))
|
||||
@@ -31,10 +31,10 @@ func TestMaskManager_Split(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestMaskManager_errors(t *testing.T) {
|
||||
_, err := NewMaskManager(&pb.TestBase{}, &pb.TestManyToOneMappings{})
|
||||
_, err := NewMaskManager(MaskDestination{&pb.TestBase{}}, MaskSource{&pb.TestManyToOneMappings{}})
|
||||
assert.Error(t, err)
|
||||
_, err = NewMaskManager(&pb.TestBase{}, &pb.TestNameDoesntMap{})
|
||||
_, err = NewMaskManager(MaskDestination{&pb.TestBase{}}, MaskSource{&pb.TestNameDoesntMap{}})
|
||||
assert.Error(t, err)
|
||||
_, err = NewMaskManager(&pb.TestBase{}, &pb.TestNotEnoughFields{})
|
||||
_, err = NewMaskManager(MaskDestination{&pb.TestBase{}}, MaskSource{&pb.TestNotEnoughFields{}})
|
||||
assert.Error(t, err)
|
||||
}
|
||||
@@ -53,7 +53,7 @@ var (
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if maskManager, err = handlers.NewMaskManager(&store.Role{}, &pb.Role{}); err != nil {
|
||||
if maskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&store.Role{}}, handlers.MaskSource{&pb.Role{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ var (
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if maskManager, err = handlers.NewMaskManager(&store.Scope{}, &pb.Scope{}); err != nil {
|
||||
if maskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&store.Scope{}}, handlers.MaskSource{&pb.Scope{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ package targets
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
stderrors "errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
@@ -11,6 +13,8 @@ import (
|
||||
"github.com/golang/protobuf/ptypes/wrappers"
|
||||
"github.com/hashicorp/boundary/globals"
|
||||
"github.com/hashicorp/boundary/internal/auth"
|
||||
"github.com/hashicorp/boundary/internal/credential"
|
||||
"github.com/hashicorp/boundary/internal/credential/vault"
|
||||
"github.com/hashicorp/boundary/internal/db/timestamp"
|
||||
"github.com/hashicorp/boundary/internal/errors"
|
||||
pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/targets"
|
||||
@@ -53,6 +57,9 @@ var (
|
||||
action.AddHostSets,
|
||||
action.SetHostSets,
|
||||
action.RemoveHostSets,
|
||||
action.AddCredentialLibraries,
|
||||
action.SetCredentialLibraries,
|
||||
action.RemoveCredentialLibraries,
|
||||
action.AuthorizeSession,
|
||||
}
|
||||
|
||||
@@ -66,7 +73,7 @@ var (
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if maskManager, err = handlers.NewMaskManager(&store.TcpTarget{}, &pb.Target{}, &pb.TcpTargetAttributes{}); err != nil {
|
||||
if maskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&store.TcpTarget{}}, handlers.MaskSource{&pb.Target{}, &pb.TcpTargetAttributes{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@@ -80,6 +87,7 @@ type Service struct {
|
||||
serversRepoFn common.ServersRepoFactory
|
||||
sessionRepoFn common.SessionRepoFactory
|
||||
staticHostRepoFn common.StaticRepoFactory
|
||||
vaultCredRepoFn common.VaultCredentialRepoFactory
|
||||
kmsCache *kms.Kms
|
||||
}
|
||||
|
||||
@@ -90,7 +98,8 @@ func NewService(
|
||||
iamRepoFn common.IamRepoFactory,
|
||||
serversRepoFn common.ServersRepoFactory,
|
||||
sessionRepoFn common.SessionRepoFactory,
|
||||
staticHostRepoFn common.StaticRepoFactory) (Service, error) {
|
||||
staticHostRepoFn common.StaticRepoFactory,
|
||||
vaultCredRepoFn common.VaultCredentialRepoFactory) (Service, error) {
|
||||
const op = "targets.NewService"
|
||||
if repoFn == nil {
|
||||
return Service{}, errors.New(errors.InvalidParameter, op, "missing target repository")
|
||||
@@ -107,12 +116,16 @@ func NewService(
|
||||
if staticHostRepoFn == nil {
|
||||
return Service{}, errors.New(errors.InvalidParameter, op, "missing static host repository")
|
||||
}
|
||||
if vaultCredRepoFn == nil {
|
||||
return Service{}, errors.New(errors.InvalidParameter, op, "missing vault credential repository")
|
||||
}
|
||||
return Service{
|
||||
repoFn: repoFn,
|
||||
iamRepoFn: iamRepoFn,
|
||||
serversRepoFn: serversRepoFn,
|
||||
sessionRepoFn: sessionRepoFn,
|
||||
staticHostRepoFn: staticHostRepoFn,
|
||||
vaultCredRepoFn: vaultCredRepoFn,
|
||||
kmsCache: kmsCache,
|
||||
}, nil
|
||||
}
|
||||
@@ -181,7 +194,7 @@ func (s Service) ListTargets(ctx context.Context, req *pbs.ListTargetsRequest) (
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authorizedActions))
|
||||
}
|
||||
|
||||
item, err := toProto(ctx, item, nil, outputOpts...)
|
||||
item, err := toProto(ctx, item, nil, nil, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -204,7 +217,7 @@ func (s Service) GetTarget(ctx context.Context, req *pbs.GetTargetRequest) (*pbs
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
t, ts, err := s.getFromRepo(ctx, req.GetId())
|
||||
t, ts, cl, err := s.getFromRepo(ctx, req.GetId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -223,7 +236,7 @@ func (s Service) GetTarget(ctx context.Context, req *pbs.GetTargetRequest) (*pbs
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings()))
|
||||
}
|
||||
|
||||
item, err := toProto(ctx, t, ts, outputOpts...)
|
||||
item, err := toProto(ctx, t, ts, cl, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -242,7 +255,7 @@ func (s Service) CreateTarget(ctx context.Context, req *pbs.CreateTargetRequest)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
t, ts, err := s.createInRepo(ctx, req.GetItem())
|
||||
t, ts, cl, err := s.createInRepo(ctx, req.GetItem())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -261,7 +274,7 @@ func (s Service) CreateTarget(ctx context.Context, req *pbs.CreateTargetRequest)
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings()))
|
||||
}
|
||||
|
||||
item, err := toProto(ctx, t, ts, outputOpts...)
|
||||
item, err := toProto(ctx, t, ts, cl, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -280,7 +293,7 @@ func (s Service) UpdateTarget(ctx context.Context, req *pbs.UpdateTargetRequest)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
t, ts, err := s.updateInRepo(ctx, authResults.Scope.GetId(), req.GetId(), req.GetUpdateMask().GetPaths(), req.GetItem())
|
||||
t, ts, cl, err := s.updateInRepo(ctx, authResults.Scope.GetId(), req.GetId(), req.GetUpdateMask().GetPaths(), req.GetItem())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -299,7 +312,7 @@ func (s Service) UpdateTarget(ctx context.Context, req *pbs.UpdateTargetRequest)
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings()))
|
||||
}
|
||||
|
||||
item, err := toProto(ctx, t, ts, outputOpts...)
|
||||
item, err := toProto(ctx, t, ts, cl, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -327,14 +340,14 @@ func (s Service) DeleteTarget(ctx context.Context, req *pbs.DeleteTargetRequest)
|
||||
func (s Service) AddTargetHostSets(ctx context.Context, req *pbs.AddTargetHostSetsRequest) (*pbs.AddTargetHostSetsResponse, error) {
|
||||
const op = "targets.(Service).AddTargetHostSets"
|
||||
|
||||
if err := validateAddRequest(req); err != nil {
|
||||
if err := validateAddSetsRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetId(), action.AddHostSets)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
t, ts, err := s.addInRepo(ctx, req.GetId(), req.GetHostSetIds(), req.GetVersion())
|
||||
t, ts, cl, err := s.addSetsInRepo(ctx, req.GetId(), req.GetHostSetIds(), req.GetVersion())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -353,7 +366,7 @@ func (s Service) AddTargetHostSets(ctx context.Context, req *pbs.AddTargetHostSe
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings()))
|
||||
}
|
||||
|
||||
item, err := toProto(ctx, t, ts, outputOpts...)
|
||||
item, err := toProto(ctx, t, ts, cl, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -365,14 +378,14 @@ func (s Service) AddTargetHostSets(ctx context.Context, req *pbs.AddTargetHostSe
|
||||
func (s Service) SetTargetHostSets(ctx context.Context, req *pbs.SetTargetHostSetsRequest) (*pbs.SetTargetHostSetsResponse, error) {
|
||||
const op = "targets.(Service).SetTargetHostSets"
|
||||
|
||||
if err := validateSetRequest(req); err != nil {
|
||||
if err := validateSetSetsRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetId(), action.SetHostSets)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
t, ts, err := s.setInRepo(ctx, req.GetId(), req.GetHostSetIds(), req.GetVersion())
|
||||
t, ts, cl, err := s.setSetsInRepo(ctx, req.GetId(), req.GetHostSetIds(), req.GetVersion())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -391,7 +404,7 @@ func (s Service) SetTargetHostSets(ctx context.Context, req *pbs.SetTargetHostSe
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings()))
|
||||
}
|
||||
|
||||
item, err := toProto(ctx, t, ts, outputOpts...)
|
||||
item, err := toProto(ctx, t, ts, cl, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -403,14 +416,14 @@ func (s Service) SetTargetHostSets(ctx context.Context, req *pbs.SetTargetHostSe
|
||||
func (s Service) RemoveTargetHostSets(ctx context.Context, req *pbs.RemoveTargetHostSetsRequest) (*pbs.RemoveTargetHostSetsResponse, error) {
|
||||
const op = "targets.(Service).RemoveTargetHostSets"
|
||||
|
||||
if err := validateRemoveRequest(req); err != nil {
|
||||
if err := validateRemoveSetsRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetId(), action.RemoveHostSets)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
t, ts, err := s.removeInRepo(ctx, req.GetId(), req.GetHostSetIds(), req.GetVersion())
|
||||
t, ts, cl, err := s.removeSetsInRepo(ctx, req.GetId(), req.GetHostSetIds(), req.GetVersion())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -429,7 +442,7 @@ func (s Service) RemoveTargetHostSets(ctx context.Context, req *pbs.RemoveTarget
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings()))
|
||||
}
|
||||
|
||||
item, err := toProto(ctx, t, ts, outputOpts...)
|
||||
item, err := toProto(ctx, t, ts, cl, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -437,6 +450,120 @@ func (s Service) RemoveTargetHostSets(ctx context.Context, req *pbs.RemoveTarget
|
||||
return &pbs.RemoveTargetHostSetsResponse{Item: item}, nil
|
||||
}
|
||||
|
||||
// AddTargetCredentialLibraries implements the interface pbs.TargetServiceServer.
|
||||
func (s Service) AddTargetCredentialLibraries(ctx context.Context, req *pbs.AddTargetCredentialLibrariesRequest) (*pbs.AddTargetCredentialLibrariesResponse, error) {
|
||||
const op = "targets.(Service).AddTargetCredentialLibraries"
|
||||
|
||||
if err := validateAddLibrariesRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetId(), action.AddCredentialLibraries)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
t, ts, cl, err := s.addLibrariesInRepo(ctx, req.GetId(), req.GetCredentialLibraryIds(), req.GetCredentialLibraries(), req.GetVersion())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputFields, ok := requests.OutputFields(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New(errors.Internal, op, "no request context found")
|
||||
}
|
||||
|
||||
outputOpts := make([]handlers.Option, 0, 3)
|
||||
outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields))
|
||||
if outputFields.Has(globals.ScopeField) {
|
||||
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedActionsField) {
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings()))
|
||||
}
|
||||
|
||||
item, err := toProto(ctx, t, ts, cl, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &pbs.AddTargetCredentialLibrariesResponse{Item: item}, nil
|
||||
}
|
||||
|
||||
// SetTargetCredentialLibraries implements the interface pbs.TargetServiceServer.
|
||||
func (s Service) SetTargetCredentialLibraries(ctx context.Context, req *pbs.SetTargetCredentialLibrariesRequest) (*pbs.SetTargetCredentialLibrariesResponse, error) {
|
||||
const op = "targets.(Service).SetTargetCredentialLibraries"
|
||||
|
||||
if err := validateSetLibrariesRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetId(), action.SetCredentialLibraries)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
t, ts, cl, err := s.setLibrariesInRepo(ctx, req.GetId(), req.GetCredentialLibraryIds(), req.GetCredentialLibraries(), req.GetVersion())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputFields, ok := requests.OutputFields(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New(errors.Internal, op, "no request context found")
|
||||
}
|
||||
|
||||
outputOpts := make([]handlers.Option, 0, 3)
|
||||
outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields))
|
||||
if outputFields.Has(globals.ScopeField) {
|
||||
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedActionsField) {
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings()))
|
||||
}
|
||||
|
||||
item, err := toProto(ctx, t, ts, cl, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &pbs.SetTargetCredentialLibrariesResponse{Item: item}, nil
|
||||
}
|
||||
|
||||
// RemoveTargetCredentialLibraries implements the interface pbs.TargetServiceServer.
|
||||
func (s Service) RemoveTargetCredentialLibraries(ctx context.Context, req *pbs.RemoveTargetCredentialLibrariesRequest) (*pbs.RemoveTargetCredentialLibrariesResponse, error) {
|
||||
const op = "targets.(Service).RemoveTargetCredentialLibraries"
|
||||
|
||||
if err := validateRemoveLibrariesRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetId(), action.RemoveCredentialLibraries)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
t, ts, cl, err := s.removeLibrariesInRepo(ctx, req.GetId(), req.GetCredentialLibraryIds(), req.GetVersion())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputFields, ok := requests.OutputFields(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New(errors.Internal, op, "no request context found")
|
||||
}
|
||||
|
||||
outputOpts := make([]handlers.Option, 0, 3)
|
||||
outputOpts = append(outputOpts, handlers.WithOutputFields(&outputFields))
|
||||
if outputFields.Has(globals.ScopeField) {
|
||||
outputOpts = append(outputOpts, handlers.WithScope(authResults.Scope))
|
||||
}
|
||||
if outputFields.Has(globals.AuthorizedActionsField) {
|
||||
outputOpts = append(outputOpts, handlers.WithAuthorizedActions(authResults.FetchActionSetForId(ctx, t.GetPublicId(), IdActions).Strings()))
|
||||
}
|
||||
|
||||
item, err := toProto(ctx, t, ts, cl, outputOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &pbs.RemoveTargetCredentialLibrariesResponse{Item: item}, nil
|
||||
}
|
||||
|
||||
func (s Service) AuthorizeSession(ctx context.Context, req *pbs.AuthorizeSessionRequest) (*pbs.AuthorizeSessionResponse, error) {
|
||||
const op = "targets.(Service).AuthorizeSession"
|
||||
if err := validateAuthorizeSessionRequest(req); err != nil {
|
||||
@@ -485,7 +612,7 @@ func (s Service) AuthorizeSession(ctx context.Context, req *pbs.AuthorizeSession
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t, hostSets, err := repo.LookupTarget(ctx, t.GetPublicId())
|
||||
t, hostSets, libs, err := repo.LookupTarget(ctx, t.GetPublicId())
|
||||
if err != nil {
|
||||
if errors.IsNotFoundError(err) {
|
||||
return nil, handlers.NotFoundErrorf("Target %q not found.", t.GetPublicId())
|
||||
@@ -653,19 +780,30 @@ HostSetIterationLoop:
|
||||
endpointUrl.Host = endpointHost
|
||||
}
|
||||
|
||||
var reqs []credential.Request
|
||||
var dynCreds []*session.DynamicCredential
|
||||
for _, l := range libs {
|
||||
reqs = append(reqs, credential.Request{
|
||||
SourceId: l.GetCredentialLibraryId(),
|
||||
Purpose: credential.Purpose(l.GetCredentialPurpose()),
|
||||
})
|
||||
dynCreds = append(dynCreds, session.NewDynamicCredential(l.GetCredentialLibraryId(), credential.Purpose(l.GetCredentialPurpose())))
|
||||
}
|
||||
|
||||
expTime := timestamppb.Now()
|
||||
expTime.Seconds += int64(t.GetSessionMaxSeconds())
|
||||
sessionComposition := session.ComposedOf{
|
||||
UserId: authResults.UserId,
|
||||
HostId: chosenId.hostId,
|
||||
TargetId: t.GetPublicId(),
|
||||
HostSetId: chosenId.hostSetId,
|
||||
AuthTokenId: authResults.AuthTokenId,
|
||||
ScopeId: authResults.Scope.Id,
|
||||
Endpoint: endpointUrl.String(),
|
||||
ExpirationTime: ×tamp.Timestamp{Timestamp: expTime},
|
||||
ConnectionLimit: t.GetSessionConnectionLimit(),
|
||||
WorkerFilter: t.GetWorkerFilter(),
|
||||
UserId: authResults.UserId,
|
||||
HostId: chosenId.hostId,
|
||||
TargetId: t.GetPublicId(),
|
||||
HostSetId: chosenId.hostSetId,
|
||||
AuthTokenId: authResults.AuthTokenId,
|
||||
ScopeId: authResults.Scope.Id,
|
||||
Endpoint: endpointUrl.String(),
|
||||
ExpirationTime: ×tamp.Timestamp{Timestamp: expTime},
|
||||
ConnectionLimit: t.GetSessionConnectionLimit(),
|
||||
WorkerFilter: t.GetWorkerFilter(),
|
||||
DynamicCredentials: dynCreds,
|
||||
}
|
||||
|
||||
sess, err := session.New(sessionComposition)
|
||||
@@ -681,6 +819,38 @@ HostSetIterationLoop:
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var cs []credential.Dynamic
|
||||
if len(reqs) > 0 {
|
||||
credRepo, err := s.vaultCredRepoFn()
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
cs, err = credRepo.Issue(ctx, sess.GetPublicId(), reqs)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op)
|
||||
}
|
||||
}
|
||||
|
||||
var creds []*pb.SessionCredential
|
||||
for _, c := range cs {
|
||||
l := c.Library()
|
||||
// TODO: Access the json directly from the vault response instead of re-marshalling it.
|
||||
jSecret, err := json.Marshal(c.Secret())
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, op, errors.WithMsg("marshalling secret to json"))
|
||||
}
|
||||
creds = append(creds, &pb.SessionCredential{
|
||||
CredentialLibrary: &pb.CredentialLibrary{
|
||||
Id: l.GetPublicId(),
|
||||
Name: l.GetName(),
|
||||
Description: l.GetDescription(),
|
||||
CredentialStoreId: l.GetStoreId(),
|
||||
Type: credential.SubtypeFromId(l.GetPublicId()).String(),
|
||||
},
|
||||
Secret: base64.StdEncoding.EncodeToString(jSecret),
|
||||
})
|
||||
}
|
||||
|
||||
sad := &pb.SessionAuthorizationData{
|
||||
SessionId: sess.PublicId,
|
||||
TargetId: t.GetPublicId(),
|
||||
@@ -711,29 +881,30 @@ HostSetIterationLoop:
|
||||
HostId: chosenId.hostId,
|
||||
HostSetId: chosenId.hostSetId,
|
||||
Endpoint: endpointUrl.String(),
|
||||
Credentials: creds,
|
||||
}
|
||||
return &pbs.AuthorizeSessionResponse{Item: ret}, nil
|
||||
}
|
||||
|
||||
func (s Service) getFromRepo(ctx context.Context, id string) (target.Target, []*target.TargetSet, error) {
|
||||
func (s Service) getFromRepo(ctx context.Context, id string) (target.Target, []*target.TargetSet, []*target.TargetLibrary, error) {
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
u, m, err := repo.LookupTarget(ctx, id)
|
||||
u, hs, cl, err := repo.LookupTarget(ctx, id)
|
||||
if err != nil {
|
||||
if errors.IsNotFoundError(err) {
|
||||
return nil, nil, handlers.NotFoundErrorf("Target %q doesn't exist.", id)
|
||||
return nil, nil, nil, handlers.NotFoundErrorf("Target %q doesn't exist.", id)
|
||||
}
|
||||
return nil, nil, err
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
if u == nil {
|
||||
return nil, nil, handlers.NotFoundErrorf("Target %q doesn't exist.", id)
|
||||
return nil, nil, nil, handlers.NotFoundErrorf("Target %q doesn't exist.", id)
|
||||
}
|
||||
return u, m, nil
|
||||
return u, hs, cl, nil
|
||||
}
|
||||
|
||||
func (s Service) createInRepo(ctx context.Context, item *pb.Target) (target.Target, []*target.TargetSet, error) {
|
||||
func (s Service) createInRepo(ctx context.Context, item *pb.Target) (target.Target, []*target.TargetSet, []*target.TargetLibrary, error) {
|
||||
const op = "targets.(Service).createInRepo"
|
||||
opts := []target.Option{target.WithName(item.GetName().GetValue())}
|
||||
if item.GetDescription() != nil {
|
||||
@@ -750,30 +921,30 @@ func (s Service) createInRepo(ctx context.Context, item *pb.Target) (target.Targ
|
||||
}
|
||||
tcpAttrs := &pb.TcpTargetAttributes{}
|
||||
if err := handlers.StructToProto(item.GetAttributes(), tcpAttrs); err != nil {
|
||||
return nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, "Provided attributes don't match expected format.")
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, "Provided attributes don't match expected format.")
|
||||
}
|
||||
if tcpAttrs.GetDefaultPort().GetValue() != 0 {
|
||||
opts = append(opts, target.WithDefaultPort(tcpAttrs.GetDefaultPort().GetValue()))
|
||||
}
|
||||
u, err := target.NewTcpTarget(item.GetScopeId(), opts...)
|
||||
if err != nil {
|
||||
return nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build target for creation: %v.", err)
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build target for creation: %v.", err)
|
||||
}
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
out, m, err := repo.CreateTcpTarget(ctx, u)
|
||||
out, hs, cl, err := repo.CreateTcpTarget(ctx, u)
|
||||
if err != nil {
|
||||
return nil, nil, errors.Wrap(err, op, errors.WithMsg("unable to create target"))
|
||||
return nil, nil, nil, errors.Wrap(err, op, errors.WithMsg("unable to create target"))
|
||||
}
|
||||
if out == nil {
|
||||
return nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create target but no error returned from repository.")
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to create target but no error returned from repository.")
|
||||
}
|
||||
return out, m, nil
|
||||
return out, hs, cl, nil
|
||||
}
|
||||
|
||||
func (s Service) updateInRepo(ctx context.Context, scopeId, id string, mask []string, item *pb.Target) (target.Target, []*target.TargetSet, error) {
|
||||
func (s Service) updateInRepo(ctx context.Context, scopeId, id string, mask []string, item *pb.Target) (target.Target, []*target.TargetSet, []*target.TargetLibrary, error) {
|
||||
const op = "targets.(Service).updateInRepo"
|
||||
var opts []target.Option
|
||||
if desc := item.GetDescription(); desc != nil {
|
||||
@@ -793,7 +964,7 @@ func (s Service) updateInRepo(ctx context.Context, scopeId, id string, mask []st
|
||||
}
|
||||
tcpAttrs := &pb.TcpTargetAttributes{}
|
||||
if err := handlers.StructToProto(item.GetAttributes(), tcpAttrs); err != nil {
|
||||
return nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, "Provided attributes don't match expected format.")
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, "Provided attributes don't match expected format.")
|
||||
}
|
||||
if tcpAttrs.GetDefaultPort().GetValue() != 0 {
|
||||
opts = append(opts, target.WithDefaultPort(tcpAttrs.GetDefaultPort().GetValue()))
|
||||
@@ -801,25 +972,25 @@ func (s Service) updateInRepo(ctx context.Context, scopeId, id string, mask []st
|
||||
version := item.GetVersion()
|
||||
u, err := target.NewTcpTarget(scopeId, opts...)
|
||||
if err != nil {
|
||||
return nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build target for update: %v.", err)
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build target for update: %v.", err)
|
||||
}
|
||||
u.PublicId = id
|
||||
dbMask := maskManager.Translate(mask)
|
||||
if len(dbMask) == 0 {
|
||||
return nil, nil, handlers.InvalidArgumentErrorf("No valid fields included in the update mask.", map[string]string{"update_mask": "No valid paths provided in the update mask."})
|
||||
return nil, nil, nil, handlers.InvalidArgumentErrorf("No valid fields included in the update mask.", map[string]string{"update_mask": "No valid paths provided in the update mask."})
|
||||
}
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
out, m, rowsUpdated, err := repo.UpdateTcpTarget(ctx, u, version, dbMask)
|
||||
out, hs, cl, rowsUpdated, err := repo.UpdateTcpTarget(ctx, u, version, dbMask)
|
||||
if err != nil {
|
||||
return nil, nil, errors.Wrap(err, op, errors.WithMsg("unable to update target"))
|
||||
return nil, nil, nil, errors.Wrap(err, op, errors.WithMsg("unable to update target"))
|
||||
}
|
||||
if rowsUpdated == 0 {
|
||||
return nil, nil, handlers.NotFoundErrorf("Target %q not found or incorrect version provided.", id)
|
||||
return nil, nil, nil, handlers.NotFoundErrorf("Target %q not found or incorrect version provided.", id)
|
||||
}
|
||||
return out, m, nil
|
||||
return out, hs, cl, nil
|
||||
}
|
||||
|
||||
func (s Service) deleteFromRepo(ctx context.Context, id string) (bool, error) {
|
||||
@@ -850,63 +1021,132 @@ func (s Service) listFromRepo(ctx context.Context, scopeIds []string) ([]target.
|
||||
return ul, nil
|
||||
}
|
||||
|
||||
func (s Service) addInRepo(ctx context.Context, targetId string, hostSetId []string, version uint32) (target.Target, []*target.TargetSet, error) {
|
||||
func (s Service) addSetsInRepo(ctx context.Context, targetId string, hostSetId []string, version uint32) (target.Target, []*target.TargetSet, []*target.TargetLibrary, error) {
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
out, m, err := repo.AddTargetHostSets(ctx, targetId, version, strutil.RemoveDuplicates(hostSetId, false))
|
||||
out, hs, cl, err := repo.AddTargetHostSets(ctx, targetId, version, strutil.RemoveDuplicates(hostSetId, false))
|
||||
if err != nil {
|
||||
// TODO: Figure out a way to surface more helpful error info beyond the Internal error.
|
||||
return nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to add host sets to target: %v.", err)
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to add host sets to target: %v.", err)
|
||||
}
|
||||
if out == nil {
|
||||
return nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to lookup target after adding host sets to it.")
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to lookup target after adding host sets to it.")
|
||||
}
|
||||
return out, m, nil
|
||||
return out, hs, cl, nil
|
||||
}
|
||||
|
||||
func (s Service) setInRepo(ctx context.Context, targetId string, hostSetIds []string, version uint32) (target.Target, []*target.TargetSet, error) {
|
||||
const op = "targets.(Service).setInRepo"
|
||||
func (s Service) setSetsInRepo(ctx context.Context, targetId string, hostSetIds []string, version uint32) (target.Target, []*target.TargetSet, []*target.TargetLibrary, error) {
|
||||
const op = "targets.(Service).setSetsInRepo"
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
_, _, err = repo.SetTargetHostSets(ctx, targetId, version, strutil.RemoveDuplicates(hostSetIds, false))
|
||||
_, _, _, err = repo.SetTargetHostSets(ctx, targetId, version, strutil.RemoveDuplicates(hostSetIds, false))
|
||||
if err != nil {
|
||||
// TODO: Figure out a way to surface more helpful error info beyond the Internal error.
|
||||
return nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to set host sets in target: %v.", err)
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to set host sets in target: %v.", err)
|
||||
}
|
||||
|
||||
out, m, err := repo.LookupTarget(ctx, targetId)
|
||||
out, hs, cl, err := repo.LookupTarget(ctx, targetId)
|
||||
if err != nil {
|
||||
return nil, nil, errors.Wrap(err, op, errors.WithMsg("unable to look up target after setting host sets"))
|
||||
return nil, nil, nil, errors.Wrap(err, op, errors.WithMsg("unable to look up target after setting host sets"))
|
||||
}
|
||||
if out == nil {
|
||||
return nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to lookup target after setting host sets for it.")
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to lookup target after setting host sets for it.")
|
||||
}
|
||||
return out, m, nil
|
||||
return out, hs, cl, nil
|
||||
}
|
||||
|
||||
func (s Service) removeInRepo(ctx context.Context, targetId string, hostSetIds []string, version uint32) (target.Target, []*target.TargetSet, error) {
|
||||
const op = "targets.(Service).removeInRepo"
|
||||
func (s Service) removeSetsInRepo(ctx context.Context, targetId string, hostSetIds []string, version uint32) (target.Target, []*target.TargetSet, []*target.TargetLibrary, error) {
|
||||
const op = "targets.(Service).removeSetsInRepo"
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
_, err = repo.DeleteTargeHostSets(ctx, targetId, version, strutil.RemoveDuplicates(hostSetIds, false))
|
||||
if err != nil {
|
||||
// TODO: Figure out a way to surface more helpful error info beyond the Internal error.
|
||||
return nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to remove host sets from target: %v.", err)
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to remove host sets from target: %v.", err)
|
||||
}
|
||||
out, m, err := repo.LookupTarget(ctx, targetId)
|
||||
out, hs, cl, err := repo.LookupTarget(ctx, targetId)
|
||||
if err != nil {
|
||||
return nil, nil, errors.Wrap(err, op, errors.WithMsg("unable to look up target after removing host sets"))
|
||||
return nil, nil, nil, errors.Wrap(err, op, errors.WithMsg("unable to look up target after removing host sets"))
|
||||
}
|
||||
if out == nil {
|
||||
return nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to lookup target after removing host sets from it.")
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to lookup target after removing host sets from it.")
|
||||
}
|
||||
return out, m, nil
|
||||
return out, hs, cl, nil
|
||||
}
|
||||
|
||||
func (s Service) addLibrariesInRepo(ctx context.Context, targetId string, libraryIds []string, libraries []*pbs.CredentialLibrary, version uint32) (target.Target, []*target.TargetSet, []*target.TargetLibrary, error) {
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
lids := make([]string, 0, len(libraryIds)+len(libraries))
|
||||
lids = append(lids, libraryIds...)
|
||||
for _, l := range libraries {
|
||||
lids = append(lids, l.GetId())
|
||||
}
|
||||
out, hs, cl, err := repo.AddTargetCredentialLibraries(ctx, targetId, version, strutil.RemoveDuplicates(lids, false))
|
||||
if err != nil {
|
||||
// TODO: Figure out a way to surface more helpful error info beyond the Internal error.
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to add credential libraries to target: %v.", err)
|
||||
}
|
||||
if out == nil {
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to lookup target after adding credential libraries to it.")
|
||||
}
|
||||
return out, hs, cl, nil
|
||||
}
|
||||
|
||||
func (s Service) setLibrariesInRepo(ctx context.Context, targetId string, libraryIds []string, libraries []*pbs.CredentialLibrary, version uint32) (target.Target, []*target.TargetSet, []*target.TargetLibrary, error) {
|
||||
const op = "targets.(Service).setLibrariesInRepo"
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
lids := make([]string, 0, len(libraryIds)+len(libraries))
|
||||
lids = append(lids, libraryIds...)
|
||||
for _, l := range libraries {
|
||||
lids = append(lids, l.GetId())
|
||||
}
|
||||
_, _, _, err = repo.SetTargetCredentialLibraries(ctx, targetId, version, strutil.RemoveDuplicates(lids, false))
|
||||
if err != nil {
|
||||
// TODO: Figure out a way to surface more helpful error info beyond the Internal error.
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to set credential libraries in target: %v.", err)
|
||||
}
|
||||
|
||||
out, hs, cl, err := repo.LookupTarget(ctx, targetId)
|
||||
if err != nil {
|
||||
return nil, nil, nil, errors.Wrap(err, op, errors.WithMsg("unable to look up target after setting credential libraries"))
|
||||
}
|
||||
if out == nil {
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to lookup target after setting credential libraries for it.")
|
||||
}
|
||||
return out, hs, cl, nil
|
||||
}
|
||||
|
||||
func (s Service) removeLibrariesInRepo(ctx context.Context, targetId string, libraryIds []string, version uint32) (target.Target, []*target.TargetSet, []*target.TargetLibrary, error) {
|
||||
const op = "targets.(Service).removeLibrariesInRepo"
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
_, err = repo.DeleteTargetCredentialLibraries(ctx, targetId, version, strutil.RemoveDuplicates(libraryIds, false))
|
||||
if err != nil {
|
||||
// TODO: Figure out a way to surface more helpful error info beyond the Internal error.
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to remove credential libraries from target: %v.", err)
|
||||
}
|
||||
out, hs, cl, err := repo.LookupTarget(ctx, targetId)
|
||||
if err != nil {
|
||||
return nil, nil, nil, errors.Wrap(err, op, errors.WithMsg("unable to look up target after removing credential libraries"))
|
||||
}
|
||||
if out == nil {
|
||||
return nil, nil, nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to lookup target after removing credential libraries from it.")
|
||||
}
|
||||
return out, hs, cl, nil
|
||||
}
|
||||
|
||||
func (s Service) authResult(ctx context.Context, id string, a action.Type, lookupOpt ...target.Option) auth.VerifyResults {
|
||||
@@ -938,7 +1178,7 @@ func (s Service) authResult(ctx context.Context, id string, a action.Type, looku
|
||||
res.Error = err
|
||||
return res
|
||||
}
|
||||
t, _, err = repo.LookupTarget(ctx, id, lookupOpt...)
|
||||
t, _, _, err = repo.LookupTarget(ctx, id, lookupOpt...)
|
||||
if err != nil {
|
||||
// TODO: Fix this with new/better error handling
|
||||
if strings.Contains(err.Error(), "more than one row returned by a subquery") {
|
||||
@@ -962,7 +1202,7 @@ func (s Service) authResult(ctx context.Context, id string, a action.Type, looku
|
||||
return ret
|
||||
}
|
||||
|
||||
func toProto(ctx context.Context, in target.Target, m []*target.TargetSet, opt ...handlers.Option) (*pb.Target, error) {
|
||||
func toProto(ctx context.Context, in target.Target, m []*target.TargetSet, l []*target.TargetLibrary, opt ...handlers.Option) (*pb.Target, error) {
|
||||
opts := handlers.GetOpts(opt...)
|
||||
if opts.WithOutputFields == nil {
|
||||
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "output fields not found when building target proto")
|
||||
@@ -1022,6 +1262,20 @@ func toProto(ctx context.Context, in target.Target, m []*target.TargetSet, opt .
|
||||
})
|
||||
}
|
||||
}
|
||||
if outputFields.Has(globals.CredentialLibraryIdsField) {
|
||||
for _, cl := range l {
|
||||
out.CredentialLibraryIds = append(out.CredentialLibraryIds, cl.GetCredentialLibraryId())
|
||||
}
|
||||
}
|
||||
if outputFields.Has(globals.CredentialLibrariesField) {
|
||||
for _, cl := range l {
|
||||
out.CredentialLibraries = append(out.CredentialLibraries, &pb.CredentialLibrary{
|
||||
Id: cl.GetCredentialLibraryId(),
|
||||
CredentialStoreId: cl.StoreId,
|
||||
Purpose: cl.GetCredentialPurpose(),
|
||||
})
|
||||
}
|
||||
}
|
||||
if outputFields.Has(globals.AttributesField) {
|
||||
attrs := &pb.TcpTargetAttributes{}
|
||||
if in.GetDefaultPort() > 0 {
|
||||
@@ -1049,10 +1303,10 @@ func validateCreateRequest(req *pbs.CreateTargetRequest) error {
|
||||
return handlers.ValidateCreateRequest(req.GetItem(), func() map[string]string {
|
||||
badFields := map[string]string{}
|
||||
if !handlers.ValidId(handlers.Id(req.GetItem().GetScopeId()), scope.Project.Prefix()) {
|
||||
badFields["scope_id"] = "This field is required to have a properly formatted project scope id."
|
||||
badFields[globals.ScopeIdField] = "This field is required to have a properly formatted project scope id."
|
||||
}
|
||||
if req.GetItem().GetName() == nil || req.GetItem().GetName().GetValue() == "" {
|
||||
badFields["name"] = "This field is required."
|
||||
badFields[globals.NameField] = "This field is required."
|
||||
}
|
||||
if req.GetItem().GetSessionConnectionLimit() != nil {
|
||||
val := req.GetItem().GetSessionConnectionLimit().GetValue()
|
||||
@@ -1060,17 +1314,17 @@ func validateCreateRequest(req *pbs.CreateTargetRequest) error {
|
||||
case val == -1:
|
||||
case val > 0:
|
||||
default:
|
||||
badFields["session_connection_limit"] = "This must be -1 (unlimited) or greater than zero."
|
||||
badFields[globals.SessionConnectionLimitField] = "This must be -1 (unlimited) or greater than zero."
|
||||
}
|
||||
}
|
||||
if req.GetItem().GetSessionMaxSeconds() != nil && req.GetItem().GetSessionMaxSeconds().GetValue() == 0 {
|
||||
badFields["session_max_seconds"] = "This must be greater than zero."
|
||||
badFields[globals.SessionMaxSecondsField] = "This must be greater than zero."
|
||||
}
|
||||
switch target.SubtypeFromType(req.GetItem().GetType()) {
|
||||
case target.TcpSubtype:
|
||||
tcpAttrs := &pb.TcpTargetAttributes{}
|
||||
if err := handlers.StructToProto(req.GetItem().GetAttributes(), tcpAttrs); err != nil {
|
||||
badFields["attributes"] = "Attribute fields do not match the expected format."
|
||||
badFields[globals.AttributesField] = "Attribute fields do not match the expected format."
|
||||
}
|
||||
if tcpAttrs.GetDefaultPort() != nil && tcpAttrs.GetDefaultPort().GetValue() == 0 {
|
||||
badFields["attributes.default_port"] = "This optional field cannot be set to 0."
|
||||
@@ -1079,13 +1333,13 @@ func validateCreateRequest(req *pbs.CreateTargetRequest) error {
|
||||
switch req.GetItem().GetType() {
|
||||
case target.TcpTargetType.String():
|
||||
case "":
|
||||
badFields["type"] = "This is a required field."
|
||||
badFields[globals.TypeField] = "This is a required field."
|
||||
default:
|
||||
badFields["type"] = "Unknown type provided."
|
||||
badFields[globals.TypeField] = "Unknown type provided."
|
||||
}
|
||||
if filter := req.GetItem().GetWorkerFilter(); filter != nil {
|
||||
if _, err := bexpr.CreateEvaluator(filter.GetValue()); err != nil {
|
||||
badFields["worker_filter"] = "Unable to successfully parse filter expression."
|
||||
badFields[globals.WorkerFilterField] = "Unable to successfully parse filter expression."
|
||||
}
|
||||
}
|
||||
return badFields
|
||||
@@ -1095,8 +1349,8 @@ func validateCreateRequest(req *pbs.CreateTargetRequest) error {
|
||||
func validateUpdateRequest(req *pbs.UpdateTargetRequest) error {
|
||||
return handlers.ValidateUpdateRequest(req, req.GetItem(), func() map[string]string {
|
||||
badFields := map[string]string{}
|
||||
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), "name") && req.GetItem().GetName().GetValue() == "" {
|
||||
badFields["name"] = "This field cannot be set to empty."
|
||||
if handlers.MaskContains(req.GetUpdateMask().GetPaths(), globals.NameField) && req.GetItem().GetName().GetValue() == "" {
|
||||
badFields[globals.NameField] = "This field cannot be set to empty."
|
||||
}
|
||||
if req.GetItem().GetSessionConnectionLimit() != nil {
|
||||
val := req.GetItem().GetSessionConnectionLimit().GetValue()
|
||||
@@ -1104,20 +1358,20 @@ func validateUpdateRequest(req *pbs.UpdateTargetRequest) error {
|
||||
case val == -1:
|
||||
case val > 0:
|
||||
default:
|
||||
badFields["session_connection_limit"] = "This must be -1 (unlimited) or greater than zero."
|
||||
badFields[globals.SessionConnectionLimitField] = "This must be -1 (unlimited) or greater than zero."
|
||||
}
|
||||
}
|
||||
if req.GetItem().GetSessionMaxSeconds() != nil && req.GetItem().GetSessionMaxSeconds().GetValue() == 0 {
|
||||
badFields["session_max_seconds"] = "This must be greater than zero."
|
||||
badFields[globals.SessionMaxSecondsField] = "This must be greater than zero."
|
||||
}
|
||||
switch target.SubtypeFromId(req.GetItem().GetType()) {
|
||||
case target.TcpSubtype:
|
||||
if req.GetItem().GetType() != "" && target.SubtypeFromType(req.GetItem().GetType()) != target.TcpSubtype {
|
||||
badFields["type"] = "Cannot modify the resource type."
|
||||
badFields[globals.TypeField] = "Cannot modify the resource type."
|
||||
}
|
||||
tcpAttrs := &pb.TcpTargetAttributes{}
|
||||
if err := handlers.StructToProto(req.GetItem().GetAttributes(), tcpAttrs); err != nil {
|
||||
badFields["attributes"] = "Attribute fields do not match the expected format."
|
||||
badFields[globals.AttributesField] = "Attribute fields do not match the expected format."
|
||||
}
|
||||
if tcpAttrs.GetDefaultPort() != nil && tcpAttrs.GetDefaultPort().GetValue() == 0 {
|
||||
badFields["attributes.default_port"] = "This optional field cannot be set to 0."
|
||||
@@ -1125,7 +1379,7 @@ func validateUpdateRequest(req *pbs.UpdateTargetRequest) error {
|
||||
}
|
||||
if filter := req.GetItem().GetWorkerFilter(); filter != nil {
|
||||
if _, err := bexpr.CreateEvaluator(filter.GetValue()); err != nil {
|
||||
badFields["worker_filter"] = "Unable to successfully parse filter expression."
|
||||
badFields[globals.WorkerFilterField] = "Unable to successfully parse filter expression."
|
||||
}
|
||||
}
|
||||
return badFields
|
||||
@@ -1140,7 +1394,7 @@ func validateListRequest(req *pbs.ListTargetsRequest) error {
|
||||
badFields := map[string]string{}
|
||||
if !handlers.ValidId(handlers.Id(req.GetScopeId()), scope.Project.Prefix()) &&
|
||||
!req.GetRecursive() {
|
||||
badFields["scope_id"] = "This field must be a valid project scope ID or the list operation must be recursive."
|
||||
badFields[globals.ScopeIdField] = "This field must be a valid project scope ID or the list operation must be recursive."
|
||||
}
|
||||
if _, err := handlers.NewFilter(req.GetFilter()); err != nil {
|
||||
badFields["filter"] = fmt.Sprintf("This field could not be parsed. %v", err)
|
||||
@@ -1151,20 +1405,20 @@ func validateListRequest(req *pbs.ListTargetsRequest) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAddRequest(req *pbs.AddTargetHostSetsRequest) error {
|
||||
func validateAddSetsRequest(req *pbs.AddTargetHostSetsRequest) error {
|
||||
badFields := map[string]string{}
|
||||
if !handlers.ValidId(handlers.Id(req.GetId()), target.TcpTargetPrefix) {
|
||||
badFields["id"] = "Incorrectly formatted identifier."
|
||||
badFields[globals.IdField] = "Incorrectly formatted identifier."
|
||||
}
|
||||
if req.GetVersion() == 0 {
|
||||
badFields["version"] = "Required field."
|
||||
badFields[globals.VersionField] = "Required field."
|
||||
}
|
||||
if len(req.GetHostSetIds()) == 0 {
|
||||
badFields["host_set_ids"] = "Must be non-empty."
|
||||
badFields[globals.HostSetIdsField] = "Must be non-empty."
|
||||
}
|
||||
for _, id := range req.GetHostSetIds() {
|
||||
if !handlers.ValidId(handlers.Id(id), static.HostSetPrefix) {
|
||||
badFields["host_set_ids"] = fmt.Sprintf("Incorrectly formatted host set identifier %q.", id)
|
||||
badFields[globals.HostSetIdsField] = fmt.Sprintf("Incorrectly formatted host set identifier %q.", id)
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -1174,17 +1428,17 @@ func validateAddRequest(req *pbs.AddTargetHostSetsRequest) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateSetRequest(req *pbs.SetTargetHostSetsRequest) error {
|
||||
func validateSetSetsRequest(req *pbs.SetTargetHostSetsRequest) error {
|
||||
badFields := map[string]string{}
|
||||
if !handlers.ValidId(handlers.Id(req.GetId()), target.TcpTargetPrefix) {
|
||||
badFields["id"] = "Incorrectly formatted identifier."
|
||||
badFields[globals.IdField] = "Incorrectly formatted identifier."
|
||||
}
|
||||
if req.GetVersion() == 0 {
|
||||
badFields["version"] = "Required field."
|
||||
badFields[globals.VersionField] = "Required field."
|
||||
}
|
||||
for _, id := range req.GetHostSetIds() {
|
||||
if !handlers.ValidId(handlers.Id(id), static.HostSetPrefix) {
|
||||
badFields["host_set_ids"] = fmt.Sprintf("Incorrectly formatted host set identifier %q.", id)
|
||||
badFields[globals.HostSetIdsField] = fmt.Sprintf("Incorrectly formatted host set identifier %q.", id)
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -1194,20 +1448,106 @@ func validateSetRequest(req *pbs.SetTargetHostSetsRequest) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateRemoveRequest(req *pbs.RemoveTargetHostSetsRequest) error {
|
||||
func validateRemoveSetsRequest(req *pbs.RemoveTargetHostSetsRequest) error {
|
||||
badFields := map[string]string{}
|
||||
if !handlers.ValidId(handlers.Id(req.GetId()), target.TcpTargetPrefix) {
|
||||
badFields["id"] = "Incorrectly formatted identifier."
|
||||
badFields[globals.IdField] = "Incorrectly formatted identifier."
|
||||
}
|
||||
if req.GetVersion() == 0 {
|
||||
badFields["version"] = "Required field."
|
||||
badFields[globals.VersionField] = "Required field."
|
||||
}
|
||||
if len(req.GetHostSetIds()) == 0 {
|
||||
badFields["host_set_ids"] = "Must be non-empty."
|
||||
badFields[globals.HostSetIdsField] = "Must be non-empty."
|
||||
}
|
||||
for _, id := range req.GetHostSetIds() {
|
||||
if !handlers.ValidId(handlers.Id(id), static.HostSetPrefix) {
|
||||
badFields["host_set_ids"] = fmt.Sprintf("Incorrectly formatted host set identifier %q.", id)
|
||||
badFields[globals.HostSetIdsField] = fmt.Sprintf("Incorrectly formatted host set identifier %q.", id)
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(badFields) > 0 {
|
||||
return handlers.InvalidArgumentErrorf("Errors in provided fields.", badFields)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateAddLibrariesRequest(req *pbs.AddTargetCredentialLibrariesRequest) error {
|
||||
badFields := map[string]string{}
|
||||
if !handlers.ValidId(handlers.Id(req.GetId()), target.TcpTargetPrefix) {
|
||||
badFields[globals.IdField] = "Incorrectly formatted identifier."
|
||||
}
|
||||
if req.GetVersion() == 0 {
|
||||
badFields[globals.VersionField] = "Required field."
|
||||
}
|
||||
if len(req.GetCredentialLibraryIds())+len(req.GetCredentialLibraries()) == 0 {
|
||||
badFields[globals.CredentialLibraryIdsField] = "Must be non-empty."
|
||||
}
|
||||
for _, id := range req.GetCredentialLibraryIds() {
|
||||
if !handlers.ValidId(handlers.Id(id), vault.CredentialLibraryPrefix) {
|
||||
badFields[globals.CredentialLibraryIdsField] = fmt.Sprintf("Incorrectly formatted credential library identifier %q.", id)
|
||||
break
|
||||
}
|
||||
}
|
||||
for _, cl := range req.GetCredentialLibraries() {
|
||||
if !handlers.ValidId(handlers.Id(cl.GetId()), vault.CredentialLibraryPrefix) {
|
||||
badFields[globals.CredentialLibrariesField] = fmt.Sprintf("Incorrectly formatted credential library identifier %q.", cl.GetId())
|
||||
break
|
||||
}
|
||||
if cl.GetPurpose() != "" && cl.GetPurpose() != string(credential.ApplicationPurpose) {
|
||||
badFields[globals.CredentialLibrariesField] = fmt.Sprintf("Unrecognized purpose %q for credential library.", cl.GetPurpose())
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(badFields) > 0 {
|
||||
return handlers.InvalidArgumentErrorf("Errors in provided fields.", badFields)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateSetLibrariesRequest(req *pbs.SetTargetCredentialLibrariesRequest) error {
|
||||
badFields := map[string]string{}
|
||||
if !handlers.ValidId(handlers.Id(req.GetId()), target.TcpTargetPrefix) {
|
||||
badFields[globals.IdField] = "Incorrectly formatted identifier."
|
||||
}
|
||||
if req.GetVersion() == 0 {
|
||||
badFields[globals.VersionField] = "Required field."
|
||||
}
|
||||
for _, id := range req.GetCredentialLibraryIds() {
|
||||
if !handlers.ValidId(handlers.Id(id), vault.CredentialLibraryPrefix) {
|
||||
badFields[globals.CredentialLibraryIdsField] = fmt.Sprintf("Incorrectly formatted credential library identifier %q.", id)
|
||||
break
|
||||
}
|
||||
}
|
||||
for _, cl := range req.GetCredentialLibraries() {
|
||||
if !handlers.ValidId(handlers.Id(cl.GetId()), vault.CredentialLibraryPrefix) {
|
||||
badFields[globals.CredentialLibrariesField] = fmt.Sprintf("Incorrectly formatted credential library identifier %q.", cl.GetId())
|
||||
break
|
||||
}
|
||||
if cl.GetPurpose() != "" && cl.GetPurpose() != string(credential.ApplicationPurpose) {
|
||||
badFields[globals.CredentialLibrariesField] = fmt.Sprintf("Unrecognized purpose %q for credential library.", cl.GetPurpose())
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(badFields) > 0 {
|
||||
return handlers.InvalidArgumentErrorf("Errors in provided fields.", badFields)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateRemoveLibrariesRequest(req *pbs.RemoveTargetCredentialLibrariesRequest) error {
|
||||
badFields := map[string]string{}
|
||||
if !handlers.ValidId(handlers.Id(req.GetId()), target.TcpTargetPrefix) {
|
||||
badFields[globals.IdField] = "Incorrectly formatted identifier."
|
||||
}
|
||||
if req.GetVersion() == 0 {
|
||||
badFields[globals.VersionField] = "Required field."
|
||||
}
|
||||
if len(req.GetCredentialLibraryIds()) == 0 {
|
||||
badFields[globals.CredentialLibraryIdsField] = "Must be non-empty."
|
||||
}
|
||||
for _, id := range req.GetCredentialLibraryIds() {
|
||||
if !handlers.ValidId(handlers.Id(id), vault.CredentialLibraryPrefix) {
|
||||
badFields[globals.CredentialLibraryIdsField] = fmt.Sprintf("Incorrectly formatted credential library identifier %q.", id)
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -1224,24 +1564,24 @@ func validateAuthorizeSessionRequest(req *pbs.AuthorizeSessionRequest) error {
|
||||
scopeNameEmpty := req.GetScopeName() == ""
|
||||
if nameEmpty {
|
||||
if !handlers.ValidId(handlers.Id(req.GetId()), target.TcpTargetPrefix) {
|
||||
badFields["id"] = "Incorrectly formatted identifier."
|
||||
badFields[globals.IdField] = "Incorrectly formatted identifier."
|
||||
}
|
||||
if !scopeIdEmpty {
|
||||
badFields["scope_id"] = "Scope ID provided when target name was empty."
|
||||
badFields[globals.ScopeIdField] = "Scope ID provided when target name was empty."
|
||||
}
|
||||
if !scopeNameEmpty {
|
||||
badFields["scope_id"] = "Scope name provided when target name was empty."
|
||||
badFields[globals.ScopeIdField] = "Scope name provided when target name was empty."
|
||||
}
|
||||
} else {
|
||||
if req.GetName() != req.GetId() {
|
||||
badFields["name"] = "Target name provided but does not match the given ID value from the URL."
|
||||
badFields[globals.NameField] = "Target name provided but does not match the given ID value from the URL."
|
||||
}
|
||||
switch {
|
||||
case scopeIdEmpty && scopeNameEmpty:
|
||||
badFields["scope_id"] = "Scope ID or scope name must be provided when target name is used."
|
||||
badFields[globals.ScopeIdField] = "Scope ID or scope name must be provided when target name is used."
|
||||
badFields["scope_name"] = "Scope ID or scope name must be provided when target name is used."
|
||||
case !scopeIdEmpty && !scopeNameEmpty:
|
||||
badFields["scope_id"] = "Scope ID and scope name cannot both be provided when target name is used."
|
||||
badFields[globals.ScopeIdField] = "Scope ID and scope name cannot both be provided when target name is used."
|
||||
badFields["scope_name"] = "Scope ID and scope name cannot both be provided when target name is used."
|
||||
}
|
||||
}
|
||||
@@ -1249,7 +1589,7 @@ func validateAuthorizeSessionRequest(req *pbs.AuthorizeSessionRequest) error {
|
||||
switch host.SubtypeFromId(req.GetHostId()) {
|
||||
case host.StaticSubtype:
|
||||
default:
|
||||
badFields["host_id"] = "Incorrectly formatted identifier."
|
||||
badFields[globals.HostIdField] = "Incorrectly formatted identifier."
|
||||
}
|
||||
}
|
||||
if len(badFields) > 0 {
|
||||
|
||||
@@ -2,26 +2,42 @@ package targets_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/boundary/internal/auth"
|
||||
"github.com/hashicorp/boundary/internal/authtoken"
|
||||
"github.com/hashicorp/boundary/internal/credential"
|
||||
"github.com/hashicorp/boundary/internal/credential/vault"
|
||||
"github.com/hashicorp/boundary/internal/db"
|
||||
credpb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/credentiallibraries"
|
||||
"github.com/hashicorp/boundary/internal/gen/controller/api/resources/scopes"
|
||||
pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/targets"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
spbs "github.com/hashicorp/boundary/internal/gen/controller/servers/services"
|
||||
"github.com/hashicorp/boundary/internal/host/static"
|
||||
"github.com/hashicorp/boundary/internal/iam"
|
||||
"github.com/hashicorp/boundary/internal/kms"
|
||||
"github.com/hashicorp/boundary/internal/requests"
|
||||
"github.com/hashicorp/boundary/internal/scheduler"
|
||||
"github.com/hashicorp/boundary/internal/servers"
|
||||
spb "github.com/hashicorp/boundary/internal/servers"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/credentiallibraries"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/targets"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/workers"
|
||||
"github.com/hashicorp/boundary/internal/session"
|
||||
"github.com/hashicorp/boundary/internal/target"
|
||||
"github.com/hashicorp/boundary/internal/types/scope"
|
||||
"github.com/hashicorp/go-hclog"
|
||||
wrapping "github.com/hashicorp/go-kms-wrapping"
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -36,10 +52,23 @@ import (
|
||||
"google.golang.org/protobuf/types/known/wrapperspb"
|
||||
)
|
||||
|
||||
var testAuthorizedActions = []string{"no-op", "read", "update", "delete", "add-host-sets", "set-host-sets", "remove-host-sets", "authorize-session"}
|
||||
var testAuthorizedActions = []string{
|
||||
"no-op",
|
||||
"read",
|
||||
"update",
|
||||
"delete",
|
||||
"add-host-sets",
|
||||
"set-host-sets",
|
||||
"remove-host-sets",
|
||||
"add-credential-libraries",
|
||||
"set-credential-libraries",
|
||||
"remove-credential-libraries",
|
||||
"authorize-session",
|
||||
}
|
||||
|
||||
func testService(t *testing.T, conn *gorm.DB, kms *kms.Kms, wrapper wrapping.Wrapper) (targets.Service, error) {
|
||||
rw := db.New(conn)
|
||||
sche := scheduler.TestScheduler(t, conn, wrapper)
|
||||
repoFn := func() (*target.Repository, error) {
|
||||
return target.NewRepository(rw, rw, kms)
|
||||
}
|
||||
@@ -55,7 +84,10 @@ func testService(t *testing.T, conn *gorm.DB, kms *kms.Kms, wrapper wrapping.Wra
|
||||
staticHostRepoFn := func() (*static.Repository, error) {
|
||||
return static.NewRepository(rw, rw, kms)
|
||||
}
|
||||
return targets.NewService(kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, staticHostRepoFn)
|
||||
credentialRepoFn := func() (*vault.Repository, error) {
|
||||
return vault.NewRepository(rw, rw, kms, sche)
|
||||
}
|
||||
return targets.NewService(kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, staticHostRepoFn, credentialRepoFn)
|
||||
}
|
||||
|
||||
func TestGet(t *testing.T) {
|
||||
@@ -534,7 +566,7 @@ func TestUpdate(t *testing.T) {
|
||||
tar, err := target.NewTcpTarget(proj.GetPublicId(), target.WithName("default"), target.WithDescription("default"))
|
||||
tar.DefaultPort = 2
|
||||
require.NoError(t, err)
|
||||
gtar, _, err := repo.CreateTcpTarget(context.Background(), tar, target.WithHostSets([]string{hs[0].GetPublicId(), hs[1].GetPublicId()}))
|
||||
gtar, _, _, err := repo.CreateTcpTarget(context.Background(), tar, target.WithHostSets([]string{hs[0].GetPublicId(), hs[1].GetPublicId()}))
|
||||
require.NoError(t, err)
|
||||
tar = gtar.(*target.TcpTarget)
|
||||
|
||||
@@ -542,7 +574,7 @@ func TestUpdate(t *testing.T) {
|
||||
|
||||
resetTarget := func() {
|
||||
version++
|
||||
_, _, _, err = repo.UpdateTcpTarget(context.Background(), tar, version, []string{"Name", "Description"})
|
||||
_, _, _, _, err = repo.UpdateTcpTarget(context.Background(), tar, version, []string{"Name", "Description"})
|
||||
require.NoError(t, err, "Failed to reset target.")
|
||||
version++
|
||||
}
|
||||
@@ -892,7 +924,7 @@ func TestUpdate_BadVersion(t *testing.T) {
|
||||
tar, err := target.NewTcpTarget(proj.GetPublicId(), target.WithName("default"), target.WithDescription("default"))
|
||||
tar.DefaultPort = 2
|
||||
require.NoError(t, err)
|
||||
gtar, _, err := repo.CreateTcpTarget(context.Background(), tar)
|
||||
gtar, _, _, err := repo.CreateTcpTarget(context.Background(), tar)
|
||||
require.NoError(t, err)
|
||||
|
||||
tested, err := testService(t, conn, kms, wrapper)
|
||||
@@ -1264,3 +1296,828 @@ func TestRemoveTargetHostSets(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddTargetLibraries(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iamRepo, nil
|
||||
}
|
||||
|
||||
_, proj := iam.TestScopes(t, iamRepo)
|
||||
|
||||
s, err := testService(t, conn, kms, wrapper)
|
||||
require.NoError(t, err, "Error when getting new target service.")
|
||||
|
||||
store := vault.TestCredentialStores(t, conn, wrapper, proj.GetPublicId(), 1)[0]
|
||||
cls := vault.TestCredentialLibraries(t, conn, wrapper, store.GetPublicId(), 2)
|
||||
|
||||
addCases := []struct {
|
||||
name string
|
||||
tar *target.TcpTarget
|
||||
addLibraryIds []string
|
||||
addLibraries []*pbs.CredentialLibrary
|
||||
resultLibraryIds []string
|
||||
}{
|
||||
{
|
||||
name: "Add set on empty target",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "empty"),
|
||||
addLibraryIds: []string{cls[1].GetPublicId()},
|
||||
resultLibraryIds: []string{cls[1].GetPublicId()},
|
||||
},
|
||||
{
|
||||
name: "Add library on populated target",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "populated", target.WithCredentialLibraries([]string{cls[0].GetPublicId()})),
|
||||
addLibraryIds: []string{cls[1].GetPublicId()},
|
||||
resultLibraryIds: []string{cls[0].GetPublicId(), cls[1].GetPublicId()},
|
||||
},
|
||||
{
|
||||
name: "Add duplicated libraries on populated target",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "duplicated", target.WithCredentialLibraries([]string{cls[0].GetPublicId()})),
|
||||
addLibraryIds: []string{cls[1].GetPublicId(), cls[1].GetPublicId()},
|
||||
resultLibraryIds: []string{cls[0].GetPublicId(), cls[1].GetPublicId()},
|
||||
},
|
||||
{
|
||||
name: "Add library on empty target",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "empty for libraries"),
|
||||
addLibraries: []*pbs.CredentialLibrary{{Id: cls[1].GetPublicId()}},
|
||||
resultLibraryIds: []string{cls[1].GetPublicId()},
|
||||
},
|
||||
{
|
||||
name: "Add library on populated target",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "populated for libraries", target.WithCredentialLibraries([]string{cls[0].GetPublicId()})),
|
||||
addLibraries: []*pbs.CredentialLibrary{{Id: cls[1].GetPublicId()}},
|
||||
resultLibraryIds: []string{cls[0].GetPublicId(), cls[1].GetPublicId()},
|
||||
},
|
||||
{
|
||||
name: "Add duplicated libraries on populated target",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "duplicated for libraries", target.WithCredentialLibraries([]string{cls[0].GetPublicId()})),
|
||||
addLibraries: []*pbs.CredentialLibrary{{Id: cls[1].GetPublicId()}, {Id: cls[1].GetPublicId()}},
|
||||
resultLibraryIds: []string{cls[0].GetPublicId(), cls[1].GetPublicId()},
|
||||
},
|
||||
{
|
||||
name: "Add duplicated libraries across 2 fields on populated target",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "duplicated mixed", target.WithCredentialLibraries([]string{cls[0].GetPublicId()})),
|
||||
addLibraryIds: []string{cls[1].GetPublicId()},
|
||||
addLibraries: []*pbs.CredentialLibrary{{Id: cls[1].GetPublicId()}},
|
||||
resultLibraryIds: []string{cls[0].GetPublicId(), cls[1].GetPublicId()},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range addCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := &pbs.AddTargetCredentialLibrariesRequest{
|
||||
Id: tc.tar.GetPublicId(),
|
||||
Version: tc.tar.GetVersion(),
|
||||
CredentialLibraryIds: tc.addLibraryIds,
|
||||
CredentialLibraries: tc.addLibraries,
|
||||
}
|
||||
|
||||
got, err := s.AddTargetCredentialLibraries(auth.DisabledAuthTestContext(iamRepoFn, proj.GetPublicId()), req)
|
||||
require.NoError(t, err, "Got error: %v", s)
|
||||
|
||||
assert.ElementsMatch(t, tc.resultLibraryIds, got.GetItem().GetCredentialLibraryIds())
|
||||
|
||||
assert.Equal(t, len(tc.resultLibraryIds), len(got.GetItem().GetCredentialLibraries()))
|
||||
|
||||
wantTemplate := &pb.CredentialLibrary{
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
Purpose: string(credential.ApplicationPurpose),
|
||||
}
|
||||
for _, cl := range got.GetItem().GetCredentialLibraries() {
|
||||
cl.Id = ""
|
||||
assert.Empty(t, cmp.Diff(wantTemplate, cl, protocmp.Transform()))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
tar := target.TestTcpTarget(t, conn, proj.GetPublicId(), "test")
|
||||
|
||||
failCases := []struct {
|
||||
name string
|
||||
req *pbs.AddTargetCredentialLibrariesRequest
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "Bad library Id",
|
||||
req: &pbs.AddTargetCredentialLibrariesRequest{
|
||||
Id: "bad id",
|
||||
Version: tar.GetVersion(),
|
||||
CredentialLibraryIds: []string{cls[0].GetPublicId()},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Bad version",
|
||||
req: &pbs.AddTargetCredentialLibrariesRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
Version: tar.GetVersion() + 2,
|
||||
CredentialLibraryIds: []string{cls[0].GetPublicId()},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.Internal),
|
||||
},
|
||||
{
|
||||
name: "Empty library list",
|
||||
req: &pbs.AddTargetCredentialLibrariesRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
Version: tar.GetVersion(),
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Incorrect library ids",
|
||||
req: &pbs.AddTargetCredentialLibrariesRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
Version: tar.GetVersion(),
|
||||
CredentialLibraryIds: []string{"incorrect"},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Incorrect library id in libraries",
|
||||
req: &pbs.AddTargetCredentialLibrariesRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
Version: tar.GetVersion(),
|
||||
CredentialLibraries: []*pbs.CredentialLibrary{{Id: "incorrect"}},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Incorrect purpose in libraries",
|
||||
req: &pbs.AddTargetCredentialLibrariesRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
Version: tar.GetVersion(),
|
||||
CredentialLibraries: []*pbs.CredentialLibrary{{Id: cls[0].GetPublicId(), Purpose: "Wrong"}},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
}
|
||||
for _, tc := range failCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
_, gErr := s.AddTargetCredentialLibraries(auth.DisabledAuthTestContext(iamRepoFn, proj.GetPublicId()), tc.req)
|
||||
if tc.err != nil {
|
||||
require.Error(gErr)
|
||||
assert.True(errors.Is(gErr, tc.err), "AddTargetCredentialLibraries(%+v) got error %v, wanted %v", tc.req, gErr, tc.err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetTargetLibraries(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iamRepo, nil
|
||||
}
|
||||
|
||||
_, proj := iam.TestScopes(t, iamRepo)
|
||||
|
||||
s, err := testService(t, conn, kms, wrapper)
|
||||
require.NoError(t, err, "Error when getting new target service.")
|
||||
|
||||
store := vault.TestCredentialStores(t, conn, wrapper, proj.GetPublicId(), 1)[0]
|
||||
cls := vault.TestCredentialLibraries(t, conn, wrapper, store.GetPublicId(), 2)
|
||||
|
||||
resultingTargetLibrary := func(id string) *pb.CredentialLibrary {
|
||||
return &pb.CredentialLibrary{
|
||||
Id: id,
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
Purpose: string(credential.ApplicationPurpose),
|
||||
}
|
||||
}
|
||||
|
||||
setCases := []struct {
|
||||
name string
|
||||
tar *target.TcpTarget
|
||||
setLibraryIds []string
|
||||
setLibraries []*pbs.CredentialLibrary
|
||||
resultLibraryIds []string
|
||||
resultLibraries []*pb.CredentialLibrary
|
||||
}{
|
||||
{
|
||||
name: "Set on empty target",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "empty"),
|
||||
setLibraryIds: []string{cls[1].GetPublicId()},
|
||||
resultLibraryIds: []string{cls[1].GetPublicId()},
|
||||
},
|
||||
{
|
||||
name: "Set on populated target",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "populated", target.WithCredentialLibraries([]string{cls[0].GetPublicId()})),
|
||||
setLibraryIds: []string{cls[1].GetPublicId()},
|
||||
resultLibraryIds: []string{cls[1].GetPublicId()},
|
||||
},
|
||||
{
|
||||
name: "Set duplicate libraries on populated target",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "duplicate", target.WithCredentialLibraries([]string{cls[0].GetPublicId()})),
|
||||
setLibraryIds: []string{cls[1].GetPublicId(), cls[1].GetPublicId()},
|
||||
resultLibraryIds: []string{cls[1].GetPublicId()},
|
||||
},
|
||||
{
|
||||
name: "Set duplicate libraries on populated target",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "duplicate with libraries", target.WithCredentialLibraries([]string{cls[0].GetPublicId()})),
|
||||
setLibraryIds: []string{cls[1].GetPublicId()},
|
||||
setLibraries: []*pbs.CredentialLibrary{{Id: cls[1].GetPublicId()}},
|
||||
resultLibraryIds: []string{cls[1].GetPublicId()},
|
||||
},
|
||||
{
|
||||
name: "Set across libraries and library",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "across fields"),
|
||||
setLibraryIds: []string{cls[0].GetPublicId()},
|
||||
setLibraries: []*pbs.CredentialLibrary{{Id: cls[1].GetPublicId()}},
|
||||
resultLibraryIds: []string{cls[0].GetPublicId(), cls[1].GetPublicId()},
|
||||
resultLibraries: []*pb.CredentialLibrary{resultingTargetLibrary(cls[0].GetPublicId()), resultingTargetLibrary(cls[1].GetPublicId())},
|
||||
},
|
||||
{
|
||||
name: "Set empty on populated target",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "another populated", target.WithCredentialLibraries([]string{cls[0].GetPublicId()})),
|
||||
setLibraryIds: []string{},
|
||||
resultLibraryIds: nil,
|
||||
},
|
||||
}
|
||||
for _, tc := range setCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := &pbs.SetTargetCredentialLibrariesRequest{
|
||||
Id: tc.tar.GetPublicId(),
|
||||
Version: tc.tar.GetVersion(),
|
||||
CredentialLibraryIds: tc.setLibraryIds,
|
||||
CredentialLibraries: tc.setLibraries,
|
||||
}
|
||||
|
||||
got, err := s.SetTargetCredentialLibraries(auth.DisabledAuthTestContext(iamRepoFn, proj.GetPublicId()), req)
|
||||
require.NoError(t, err, "Got error: %v", s)
|
||||
assert.ElementsMatch(t, tc.resultLibraryIds, got.GetItem().GetCredentialLibraryIds())
|
||||
|
||||
if len(tc.resultLibraries) != 0 {
|
||||
sort.Slice(tc.resultLibraries, func(i, j int) bool {
|
||||
return tc.resultLibraries[i].GetId() < tc.resultLibraries[j].GetId()
|
||||
})
|
||||
sort.Slice(got.GetItem().CredentialLibraries, func(i, j int) bool {
|
||||
return got.GetItem().CredentialLibraries[i].GetId() < got.GetItem().CredentialLibraries[j].GetId()
|
||||
})
|
||||
assert.Empty(t, cmp.Diff(tc.resultLibraries, got.GetItem().GetCredentialLibraries(), protocmp.Transform()))
|
||||
} else {
|
||||
assert.Equal(t, len(tc.resultLibraryIds), len(got.GetItem().GetCredentialLibraries()))
|
||||
for _, cl := range got.GetItem().GetCredentialLibraries() {
|
||||
assert.Empty(t, cmp.Diff(resultingTargetLibrary(cl.Id), cl, protocmp.Transform()))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
tar := target.TestTcpTarget(t, conn, proj.GetPublicId(), "test name")
|
||||
|
||||
failCases := []struct {
|
||||
name string
|
||||
req *pbs.SetTargetCredentialLibrariesRequest
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "Bad target Id",
|
||||
req: &pbs.SetTargetCredentialLibrariesRequest{
|
||||
Id: "bad id",
|
||||
Version: tar.GetVersion(),
|
||||
CredentialLibraryIds: []string{cls[0].GetPublicId()},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Bad version",
|
||||
req: &pbs.SetTargetCredentialLibrariesRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
Version: tar.GetVersion() + 3,
|
||||
CredentialLibraryIds: []string{cls[0].GetPublicId()},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.Internal),
|
||||
},
|
||||
{
|
||||
name: "Bad library id",
|
||||
req: &pbs.SetTargetCredentialLibrariesRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
Version: tar.GetVersion(),
|
||||
CredentialLibraryIds: []string{"invalid"},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Incorrect library id in libraries",
|
||||
req: &pbs.SetTargetCredentialLibrariesRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
Version: tar.GetVersion(),
|
||||
CredentialLibraries: []*pbs.CredentialLibrary{{Id: "incorrect"}},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Incorrect purpose in libraries",
|
||||
req: &pbs.SetTargetCredentialLibrariesRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
Version: tar.GetVersion(),
|
||||
CredentialLibraries: []*pbs.CredentialLibrary{{Id: cls[0].GetPublicId(), Purpose: "Wrong"}},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
}
|
||||
for _, tc := range failCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
_, gErr := s.SetTargetCredentialLibraries(auth.DisabledAuthTestContext(iamRepoFn, proj.GetPublicId()), tc.req)
|
||||
if tc.err != nil {
|
||||
require.Error(gErr)
|
||||
assert.True(errors.Is(gErr, tc.err), "SetTargetCredentialLibraries(%+v) got error %v, wanted %v", tc.req, gErr, tc.err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoveTargetLibraries(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iamRepo, nil
|
||||
}
|
||||
|
||||
_, proj := iam.TestScopes(t, iamRepo)
|
||||
|
||||
s, err := testService(t, conn, kms, wrapper)
|
||||
require.NoError(t, err, "Error when getting new target service.")
|
||||
|
||||
store := vault.TestCredentialStores(t, conn, wrapper, proj.GetPublicId(), 1)[0]
|
||||
cls := vault.TestCredentialLibraries(t, conn, wrapper, store.GetPublicId(), 2)
|
||||
|
||||
removeCases := []struct {
|
||||
name string
|
||||
tar *target.TcpTarget
|
||||
removeLibs []string
|
||||
resultLibs []string
|
||||
wantErr bool
|
||||
}{
|
||||
{
|
||||
name: "Remove from empty",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "empty"),
|
||||
removeLibs: []string{cls[1].GetPublicId()},
|
||||
wantErr: true,
|
||||
},
|
||||
{
|
||||
name: "Remove 1 of 2 libraries",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "remove partial", target.WithCredentialLibraries([]string{cls[0].GetPublicId(), cls[1].GetPublicId()})),
|
||||
removeLibs: []string{cls[1].GetPublicId()},
|
||||
resultLibs: []string{cls[0].GetPublicId()},
|
||||
},
|
||||
{
|
||||
name: "Remove 1 duplicate set of 2 libraries",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "remove duplicate", target.WithCredentialLibraries([]string{cls[0].GetPublicId(), cls[1].GetPublicId()})),
|
||||
removeLibs: []string{cls[1].GetPublicId(), cls[1].GetPublicId()},
|
||||
resultLibs: []string{cls[0].GetPublicId()},
|
||||
},
|
||||
{
|
||||
name: "Remove all libraries from target",
|
||||
tar: target.TestTcpTarget(t, conn, proj.GetPublicId(), "remove all", target.WithCredentialLibraries([]string{cls[0].GetPublicId(), cls[1].GetPublicId()})),
|
||||
removeLibs: []string{cls[0].GetPublicId(), cls[1].GetPublicId()},
|
||||
resultLibs: []string{},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range removeCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := &pbs.RemoveTargetCredentialLibrariesRequest{
|
||||
Id: tc.tar.GetPublicId(),
|
||||
Version: tc.tar.GetVersion(),
|
||||
CredentialLibraryIds: tc.removeLibs,
|
||||
}
|
||||
|
||||
got, err := s.RemoveTargetCredentialLibraries(auth.DisabledAuthTestContext(iamRepoFn, proj.GetPublicId()), req)
|
||||
if tc.wantErr {
|
||||
assert.Error(t, err)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err, "Got error: %v", s)
|
||||
|
||||
assert.ElementsMatch(t, tc.resultLibs, got.GetItem().GetCredentialLibraryIds())
|
||||
})
|
||||
}
|
||||
|
||||
tar := target.TestTcpTarget(t, conn, proj.GetPublicId(), "testing")
|
||||
|
||||
failCases := []struct {
|
||||
name string
|
||||
req *pbs.RemoveTargetCredentialLibrariesRequest
|
||||
err error
|
||||
}{
|
||||
{
|
||||
name: "Bad version",
|
||||
req: &pbs.RemoveTargetCredentialLibrariesRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
Version: tar.GetVersion() + 3,
|
||||
CredentialLibraryIds: []string{cls[0].GetPublicId()},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.Internal),
|
||||
},
|
||||
{
|
||||
name: "Bad target Id",
|
||||
req: &pbs.RemoveTargetCredentialLibrariesRequest{
|
||||
Id: "bad id",
|
||||
Version: tar.GetVersion(),
|
||||
CredentialLibraryIds: []string{cls[0].GetPublicId()},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "empty libraries",
|
||||
req: &pbs.RemoveTargetCredentialLibrariesRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
Version: tar.GetVersion(),
|
||||
CredentialLibraryIds: []string{},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
{
|
||||
name: "Invalid library ids",
|
||||
req: &pbs.RemoveTargetCredentialLibrariesRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
Version: tar.GetVersion(),
|
||||
CredentialLibraryIds: []string{"invalid"},
|
||||
},
|
||||
err: handlers.ApiErrorWithCode(codes.InvalidArgument),
|
||||
},
|
||||
}
|
||||
for _, tc := range failCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
_, gErr := s.RemoveTargetCredentialLibraries(auth.DisabledAuthTestContext(iamRepoFn, proj.GetPublicId()), tc.req)
|
||||
if tc.err != nil {
|
||||
require.Error(gErr)
|
||||
assert.True(errors.Is(gErr, tc.err), "RemoveTargetCredentialLibraries(%+v) got error %v, wanted %v", tc.req, gErr, tc.err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizeSession(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
|
||||
sche := scheduler.TestScheduler(t, conn, wrapper)
|
||||
repoFn := func() (*target.Repository, error) {
|
||||
return target.NewRepository(rw, rw, kms)
|
||||
}
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iamRepo, nil
|
||||
}
|
||||
serversRepoFn := func() (*servers.Repository, error) {
|
||||
return servers.NewRepository(rw, rw, kms)
|
||||
}
|
||||
sessionRepoFn := func() (*session.Repository, error) {
|
||||
return session.NewRepository(rw, rw, kms)
|
||||
}
|
||||
staticHostRepoFn := func() (*static.Repository, error) {
|
||||
return static.NewRepository(rw, rw, kms)
|
||||
}
|
||||
credentialRepoFn := func() (*vault.Repository, error) {
|
||||
return vault.NewRepository(rw, rw, kms, sche)
|
||||
}
|
||||
atRepoFn := func() (*authtoken.Repository, error) {
|
||||
return authtoken.NewRepository(rw, rw, kms)
|
||||
}
|
||||
|
||||
org, proj := iam.TestScopes(t, iamRepo)
|
||||
at := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
|
||||
ctx := auth.NewVerifierContext(requests.NewRequestContext(context.Background()),
|
||||
nil,
|
||||
iamRepoFn,
|
||||
atRepoFn,
|
||||
serversRepoFn,
|
||||
kms,
|
||||
auth.RequestInfo{
|
||||
Token: at.GetToken(),
|
||||
TokenFormat: auth.AuthTokenTypeBearer,
|
||||
PublicId: at.GetPublicId(),
|
||||
})
|
||||
|
||||
r := iam.TestRole(t, conn, proj.GetPublicId())
|
||||
_ = iam.TestUserRole(t, conn, r.GetPublicId(), at.GetIamUserId())
|
||||
_ = iam.TestRoleGrant(t, conn, r.GetPublicId(), "id=*;type=*;actions=*")
|
||||
|
||||
s, err := targets.NewService(kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, staticHostRepoFn, credentialRepoFn)
|
||||
require.NoError(t, err)
|
||||
|
||||
tar := target.TestTcpTarget(t, conn, proj.GetPublicId(), "test")
|
||||
hc := static.TestCatalogs(t, conn, proj.GetPublicId(), 1)[0]
|
||||
h := static.TestHosts(t, conn, hc.GetPublicId(), 1)[0]
|
||||
hs := static.TestSets(t, conn, hc.GetPublicId(), 1)[0]
|
||||
_ = static.TestSetMembers(t, conn, hs.GetPublicId(), []*static.Host{h})
|
||||
|
||||
apiTar, err := s.AddTargetHostSets(ctx, &pbs.AddTargetHostSetsRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
Version: tar.GetVersion(),
|
||||
HostSetIds: []string{hs.GetPublicId()},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
// Tell our DB that there is a worker ready to serve the data
|
||||
workerService := workers.NewWorkerServiceServer(hclog.Default(), serversRepoFn, sessionRepoFn, &sync.Map{}, kms)
|
||||
_, err = workerService.Status(ctx, &spbs.StatusRequest{
|
||||
Worker: &spb.Server{
|
||||
PrivateId: "testworker",
|
||||
Address: "localhost:8457",
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
v := vault.NewTestVaultServer(t)
|
||||
v.MountPKI(t)
|
||||
sec, tok := v.CreateToken(t, vault.WithPolicies([]string{"default", "boundary-controller", "pki"}))
|
||||
|
||||
store := vault.TestCredentialStore(t, conn, wrapper, proj.GetPublicId(), v.Addr, tok, sec.Auth.Accessor)
|
||||
credService, err := credentiallibraries.NewService(credentialRepoFn, iamRepoFn)
|
||||
require.NoError(t, err)
|
||||
clsResp, err := credService.CreateCredentialLibrary(ctx, &pbs.CreateCredentialLibraryRequest{Item: &credpb.CredentialLibrary{
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
Name: wrapperspb.String("Library Name"),
|
||||
Description: wrapperspb.String("Library Description"),
|
||||
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
|
||||
"path": structpb.NewStringValue(path.Join("pki", "issue", "boundary")),
|
||||
"http_method": structpb.NewStringValue("POST"),
|
||||
"http_request_body": structpb.NewStringValue(`{"common_name":"boundary.com"}`),
|
||||
}},
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = s.AddTargetCredentialLibraries(ctx,
|
||||
&pbs.AddTargetCredentialLibrariesRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
CredentialLibraryIds: []string{clsResp.GetItem().GetId()},
|
||||
Version: apiTar.GetItem().GetVersion(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
asRes1, err := s.AuthorizeSession(ctx, &pbs.AuthorizeSessionRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
asRes2, err := s.AuthorizeSession(ctx, &pbs.AuthorizeSessionRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
assert.NotEmpty(t, cmp.Diff(asRes1.GetItem().GetCredentials(), asRes2.GetItem().GetCredentials(), protocmp.Transform()),
|
||||
"the credentials aren't unique per request authorized session")
|
||||
|
||||
want := &pb.SessionAuthorization{
|
||||
Scope: &scopes.ScopeInfo{
|
||||
Id: proj.GetPublicId(),
|
||||
Type: proj.GetType(),
|
||||
Name: proj.GetName(),
|
||||
Description: proj.GetDescription(),
|
||||
ParentScopeId: proj.GetParentId(),
|
||||
},
|
||||
TargetId: tar.GetPublicId(),
|
||||
UserId: at.GetIamUserId(),
|
||||
HostSetId: hs.GetPublicId(),
|
||||
HostId: h.GetPublicId(),
|
||||
Type: "tcp",
|
||||
Endpoint: fmt.Sprintf("tcp://%s", h.GetAddress()),
|
||||
Credentials: []*pb.SessionCredential{{
|
||||
CredentialLibrary: &pb.CredentialLibrary{
|
||||
Id: clsResp.GetItem().GetId(),
|
||||
Name: clsResp.GetItem().GetName().GetValue(),
|
||||
Description: clsResp.GetItem().GetDescription().GetValue(),
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
Type: credential.VaultSubtype.String(),
|
||||
},
|
||||
}},
|
||||
// TODO: validate the contents of the authorization token is what is expected
|
||||
}
|
||||
wantSecret := map[string]interface{}{
|
||||
"certificate": "-----BEGIN CERTIFICATE-----\n",
|
||||
"issuing_ca": "-----BEGIN CERTIFICATE-----\n",
|
||||
"private_key": "-----BEGIN RSA PRIVATE KEY-----\n",
|
||||
"private_key_type": "rsa",
|
||||
}
|
||||
_ = wantSecret
|
||||
got := asRes1.GetItem()
|
||||
|
||||
require.Len(t, got.GetCredentials(), 1)
|
||||
|
||||
gotCred := got.Credentials[0]
|
||||
assert.NotEmpty(t, gotCred.Secret)
|
||||
dSec := decodeJsonSecret(t, gotCred.Secret)
|
||||
require.NoError(t, err)
|
||||
for k, v := range wantSecret {
|
||||
gotV, ok := dSec[k]
|
||||
require.True(t, ok)
|
||||
assert.Truef(t, strings.HasPrefix(gotV.(string), v.(string)), "%q:%q doesn't have prefix %q", k, gotV, v)
|
||||
}
|
||||
gotCred.Secret = ""
|
||||
|
||||
got.AuthorizationToken, got.SessionId, got.CreatedTime = "", "", nil
|
||||
assert.Empty(t, cmp.Diff(got, want, protocmp.Transform()))
|
||||
}
|
||||
|
||||
func TestAuthorizeSession_Errors(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
rw := db.New(conn)
|
||||
wrapper := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrapper)
|
||||
|
||||
sche := scheduler.TestScheduler(t, conn, wrapper)
|
||||
repoFn := func() (*target.Repository, error) {
|
||||
return target.NewRepository(rw, rw, kms)
|
||||
}
|
||||
iamRepo := iam.TestRepo(t, conn, wrapper)
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iamRepo, nil
|
||||
}
|
||||
serversRepoFn := func() (*servers.Repository, error) {
|
||||
return servers.NewRepository(rw, rw, kms)
|
||||
}
|
||||
sessionRepoFn := func() (*session.Repository, error) {
|
||||
return session.NewRepository(rw, rw, kms)
|
||||
}
|
||||
staticHostRepoFn := func() (*static.Repository, error) {
|
||||
return static.NewRepository(rw, rw, kms)
|
||||
}
|
||||
credentialRepoFn := func() (*vault.Repository, error) {
|
||||
return vault.NewRepository(rw, rw, kms, sche)
|
||||
}
|
||||
atRepoFn := func() (*authtoken.Repository, error) {
|
||||
return authtoken.NewRepository(rw, rw, kms)
|
||||
}
|
||||
org, proj := iam.TestScopes(t, iamRepo)
|
||||
|
||||
s, err := targets.NewService(kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, staticHostRepoFn, credentialRepoFn)
|
||||
require.NoError(t, err)
|
||||
|
||||
// Authorized user gets full permissions
|
||||
at := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
|
||||
ctx := auth.NewVerifierContext(requests.NewRequestContext(context.Background()),
|
||||
nil,
|
||||
iamRepoFn,
|
||||
atRepoFn,
|
||||
serversRepoFn,
|
||||
kms,
|
||||
auth.RequestInfo{
|
||||
Token: at.GetToken(),
|
||||
TokenFormat: auth.AuthTokenTypeBearer,
|
||||
PublicId: at.GetPublicId(),
|
||||
})
|
||||
r := iam.TestRole(t, conn, proj.GetPublicId())
|
||||
_ = iam.TestUserRole(t, conn, r.GetPublicId(), at.GetIamUserId())
|
||||
_ = iam.TestRoleGrant(t, conn, r.GetPublicId(), "id=*;type=*;actions=*")
|
||||
|
||||
v := vault.NewTestVaultServer(t, vault.WithDockerNetwork(true))
|
||||
v.MountDatabase(t)
|
||||
sec, tok := v.CreateToken(t, vault.WithPolicies([]string{"default", "database"}))
|
||||
store := vault.TestCredentialStore(t, conn, wrapper, proj.GetPublicId(), v.Addr, tok, sec.Auth.Accessor)
|
||||
|
||||
workerExists := func(tar *target.TcpTarget) (version uint32) {
|
||||
workerService := workers.NewWorkerServiceServer(hclog.Default(), serversRepoFn, sessionRepoFn, &sync.Map{}, kms)
|
||||
_, err := workerService.Status(context.Background(), &spbs.StatusRequest{
|
||||
Worker: &spb.Server{
|
||||
PrivateId: "testworker",
|
||||
Address: "localhost:123",
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return tar.GetVersion()
|
||||
}
|
||||
|
||||
hostSetNoHostExists := func(tar *target.TcpTarget) (version uint32) {
|
||||
hc := static.TestCatalogs(t, conn, proj.GetPublicId(), 1)[0]
|
||||
hs := static.TestSets(t, conn, hc.GetPublicId(), 1)[0]
|
||||
|
||||
tr, err := s.AddTargetHostSets(ctx, &pbs.AddTargetHostSetsRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
Version: tar.GetVersion(),
|
||||
HostSetIds: []string{hs.GetPublicId()},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return tr.GetItem().GetVersion()
|
||||
}
|
||||
|
||||
hostExists := func(tar *target.TcpTarget) (version uint32) {
|
||||
hc := static.TestCatalogs(t, conn, proj.GetPublicId(), 1)[0]
|
||||
h := static.TestHosts(t, conn, hc.GetPublicId(), 1)[0]
|
||||
hs := static.TestSets(t, conn, hc.GetPublicId(), 1)[0]
|
||||
_ = static.TestSetMembers(t, conn, hs.GetPublicId(), []*static.Host{h})
|
||||
apiTar, err := s.AddTargetHostSets(ctx, &pbs.AddTargetHostSetsRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
Version: tar.GetVersion(),
|
||||
HostSetIds: []string{hs.GetPublicId()},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return apiTar.GetItem().GetVersion()
|
||||
}
|
||||
|
||||
libraryExists := func(tar *target.TcpTarget) (version uint32) {
|
||||
credService, err := credentiallibraries.NewService(credentialRepoFn, iamRepoFn)
|
||||
require.NoError(t, err)
|
||||
clsResp, err := credService.CreateCredentialLibrary(ctx, &pbs.CreateCredentialLibraryRequest{Item: &credpb.CredentialLibrary{
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
Description: wrapperspb.String(fmt.Sprintf("Library Description for target %q", tar.GetName())),
|
||||
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
|
||||
"path": structpb.NewStringValue(path.Join("database", "creds", "opened")),
|
||||
}},
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
|
||||
tr, err := s.AddTargetCredentialLibraries(ctx,
|
||||
&pbs.AddTargetCredentialLibrariesRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
CredentialLibraryIds: []string{clsResp.GetItem().GetId()},
|
||||
Version: tar.GetVersion(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return tr.GetItem().GetVersion()
|
||||
}
|
||||
|
||||
misConfiguredlibraryExists := func(tar *target.TcpTarget) (version uint32) {
|
||||
credService, err := credentiallibraries.NewService(credentialRepoFn, iamRepoFn)
|
||||
require.NoError(t, err)
|
||||
clsResp, err := credService.CreateCredentialLibrary(ctx, &pbs.CreateCredentialLibraryRequest{Item: &credpb.CredentialLibrary{
|
||||
CredentialStoreId: store.GetPublicId(),
|
||||
Description: wrapperspb.String(fmt.Sprintf("Library Description for target %q", tar.GetName())),
|
||||
Attributes: &structpb.Struct{Fields: map[string]*structpb.Value{
|
||||
"path": structpb.NewStringValue("bad path"),
|
||||
}},
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
|
||||
tr, err := s.AddTargetCredentialLibraries(ctx,
|
||||
&pbs.AddTargetCredentialLibrariesRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
CredentialLibraryIds: []string{clsResp.GetItem().GetId()},
|
||||
Version: tar.GetVersion(),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return tr.GetItem().GetVersion()
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
setup []func(*target.TcpTarget) uint32
|
||||
err bool
|
||||
}{
|
||||
{
|
||||
// This one must be run first since it relies on the DB not having any worker details
|
||||
name: "no worker",
|
||||
setup: []func(tcpTarget *target.TcpTarget) uint32{hostExists, libraryExists},
|
||||
err: true,
|
||||
},
|
||||
{
|
||||
name: "success",
|
||||
setup: []func(tcpTarget *target.TcpTarget) uint32{workerExists, hostExists, libraryExists},
|
||||
},
|
||||
{
|
||||
name: "no hosts",
|
||||
setup: []func(tcpTarget *target.TcpTarget) uint32{workerExists, hostSetNoHostExists, libraryExists},
|
||||
err: true,
|
||||
},
|
||||
{
|
||||
name: "bad library configuration",
|
||||
setup: []func(tcpTarget *target.TcpTarget) uint32{workerExists, hostExists, misConfiguredlibraryExists},
|
||||
err: true,
|
||||
},
|
||||
}
|
||||
for i, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
tar := target.TestTcpTarget(t, conn, proj.GetPublicId(), fmt.Sprintf("test-%d", i))
|
||||
|
||||
for _, fn := range tc.setup {
|
||||
ver := fn(tar)
|
||||
tar.Version = ver
|
||||
}
|
||||
|
||||
res, err := s.AuthorizeSession(ctx, &pbs.AuthorizeSessionRequest{
|
||||
Id: tar.GetPublicId(),
|
||||
})
|
||||
if tc.err {
|
||||
require.Error(t, err)
|
||||
require.Nil(t, res)
|
||||
return
|
||||
}
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, res)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func decodeJsonSecret(t *testing.T, in string) map[string]interface{} {
|
||||
t.Helper()
|
||||
ret := make(map[string]interface{})
|
||||
dec := json.NewDecoder(base64.NewDecoder(base64.StdEncoding, strings.NewReader(in)))
|
||||
dec.UseNumber()
|
||||
require.NoError(t, dec.Decode(&ret))
|
||||
return ret
|
||||
}
|
||||
@@ -51,7 +51,7 @@ var (
|
||||
|
||||
func init() {
|
||||
var err error
|
||||
if maskManager, err = handlers.NewMaskManager(&store.User{}, &pb.User{}); err != nil {
|
||||
if maskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&store.User{}}, handlers.MaskSource{&pb.User{}}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user