Add authorize session for plugin based host sets. (#1559)

Added a new Endpoint struct at the top level host package level to capture host, set, and address chosen.
Temporarily add a host_plugin_host table to capture the hosts returned by the plugins.  This ensures the datawarehouse is able to query the table to decide what host was chosen.  The view used to update the datawarehouse dimension table provides rows with host set ids and hosts which are not in that host set.  This is ok since the function which updates the dimension table provides the host set and host id chosen so that relationship doesn't need to be captured in the view itself.

Co-authored-by: Jeff Mitchell <jeffrey.mitchell@gmail.com>
This commit is contained in:
ToddandJeff Mitchell authored and GitHub committed 2021-09-26 11:17:21 -04:00
1 parent 8b8f5de120
commit 14cc97b645
18 files changed
+1536 -332

No files matched your search

+2
View File
@@ -142,11 +142,13 @@ func handleGrpcGateway(c *Controller, props HandlerProperties) (http.Handler, er
return nil, fmt.Errorf("failed to register user service handler: %w", err)
}
ts, err := targets.NewService(
ctx,
c.kms,
c.TargetRepoFn,
c.IamRepoFn,
c.ServersRepoFn,
c.SessionRepoFn,
c.PluginHostRepoFn,
c.StaticHostRepoFn,
c.VaultCredentialRepoFn)
if err != nil {
@@ -91,6 +91,7 @@ type Service struct {
iamRepoFn common.IamRepoFactory
serversRepoFn common.ServersRepoFactory
sessionRepoFn common.SessionRepoFactory
pluginHostRepoFn common.PluginHostRepoFactory
staticHostRepoFn common.StaticRepoFactory
vaultCredRepoFn common.VaultCredentialRepoFactory
kmsCache *kms.Kms
@@ -98,37 +99,43 @@ type Service struct {
// NewService returns a target service which handles target related requests to boundary.
func NewService(
ctx context.Context,
kmsCache *kms.Kms,
repoFn common.TargetRepoFactory,
iamRepoFn common.IamRepoFactory,
serversRepoFn common.ServersRepoFactory,
sessionRepoFn common.SessionRepoFactory,
pluginHostRepoFn common.PluginHostRepoFactory,
staticHostRepoFn common.StaticRepoFactory,
vaultCredRepoFn common.VaultCredentialRepoFactory) (Service, error) {
const op = "targets.NewService"
if repoFn == nil {
return Service{}, errors.NewDeprecated(errors.InvalidParameter, op, "missing target repository")
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing target repository")
}
if iamRepoFn == nil {
return Service{}, errors.NewDeprecated(errors.InvalidParameter, op, "missing iam repository")
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing iam repository")
}
if serversRepoFn == nil {
return Service{}, errors.NewDeprecated(errors.InvalidParameter, op, "missing servers repository")
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing servers repository")
}
if sessionRepoFn == nil {
return Service{}, errors.NewDeprecated(errors.InvalidParameter, op, "missing session repository")
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing session repository")
}
if pluginHostRepoFn == nil {
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing plugin host repository")
}
if staticHostRepoFn == nil {
return Service{}, errors.NewDeprecated(errors.InvalidParameter, op, "missing static host repository")
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing static host repository")
}
if vaultCredRepoFn == nil {
return Service{}, errors.NewDeprecated(errors.InvalidParameter, op, "missing vault credential repository")
return Service{}, errors.New(ctx, errors.InvalidParameter, op, "missing vault credential repository")
}
return Service{
repoFn: repoFn,
iamRepoFn: iamRepoFn,
serversRepoFn: serversRepoFn,
sessionRepoFn: sessionRepoFn,
pluginHostRepoFn: pluginHostRepoFn,
staticHostRepoFn: staticHostRepoFn,
vaultCredRepoFn: vaultCredRepoFn,
kmsCache: kmsCache,
@@ -940,55 +947,65 @@ func (s Service) AuthorizeSession(ctx context.Context, req *pbs.AuthorizeSession
"No workers are available to handle this session, or all have been filtered.")
}
// First, fetch all available hosts. Unless one was chosen in the request,
// we will pick one at random.
type compoundHost struct {
hostSetId string
hostId string
}
var chosenId *compoundHost
requestedId := req.GetHostId()
staticHostRepo, err := s.staticHostRepoFn()
if err != nil {
return nil, err
}
pluginHostRepo, err := s.pluginHostRepoFn()
if err != nil {
return nil, err
}
hostIds := make([]compoundHost, 0, len(hostSources)*10)
HostSourceIterationLoop:
var pluginHostSetIds []string
var endpoints []*host.Endpoint
for _, hSource := range hostSources {
hsId := hSource.Id()
// FIXME: read in type from DB rather than rely on prefix
switch host.SubtypeFromId(hsId) {
case static.Subtype:
_, hosts, err := staticHostRepo.LookupSet(ctx, hsId)
eps, err := staticHostRepo.Endpoints(ctx, hsId)
if err != nil {
return nil, err
}
for _, host := range hosts {
compoundId := compoundHost{hostSetId: hsId, hostId: host.PublicId}
hostIds = append(hostIds, compoundId)
if host.PublicId == requestedId {
chosenId = &compoundId
break HostSourceIterationLoop
}
endpoints = append(endpoints, eps...)
default:
// Batch the plugin host set ids since each round trip to the plugin
// has the potential to be expensive.
pluginHostSetIds = append(pluginHostSetIds, hsId)
}
}
if len(pluginHostSetIds) > 0 {
eps, err := pluginHostRepo.Endpoints(ctx, pluginHostSetIds)
if err != nil {
return nil, err
}
endpoints = append(endpoints, eps...)
}
var chosenEndpoint *host.Endpoint
if requestedId != "" {
for _, ep := range endpoints {
if ep.HostId == requestedId {
chosenEndpoint = ep
}
}
}
if requestedId != "" && chosenId == nil {
// We didn't find it
return nil, handlers.InvalidArgumentErrorf(
"Errors in provided fields.",
map[string]string{
"host_id": "The requested host id is not available.",
})
}
if chosenId == nil {
if len(hostIds) == 0 {
// No hosts were found, error
return nil, handlers.NotFoundErrorf("No hosts found from available target host sources.")
if chosenEndpoint == nil {
// We didn't find it
return nil, handlers.InvalidArgumentErrorf(
"Errors in provided fields.",
map[string]string{
"host_id": "The requested host id is not available.",
})
}
chosenId = &hostIds[rand.Intn(len(hostIds))]
}
if chosenEndpoint == nil {
if len(endpoints) == 0 {
// No hosts were found, error
return nil, handlers.NotFoundErrorf("No endpoint found from available target host sources.")
}
chosenEndpoint = endpoints[rand.Intn(len(endpoints))]
}
// Generate the endpoint URL
@@ -996,22 +1013,10 @@ HostSourceIterationLoop:
Scheme: t.GetType(),
}
defaultPort := t.GetDefaultPort()
var endpointHost string
switch host.SubtypeFromId(chosenId.hostId) {
case static.Subtype:
h, err := staticHostRepo.LookupHost(ctx, chosenId.hostId)
if err != nil {
return nil, errors.New(ctx, errors.InvalidParameter, op, "errors looking up host")
}
endpointHost = h.Address
if endpointHost == "" {
return nil, stderrors.New("host had empty address")
}
}
if defaultPort != 0 {
endpointUrl.Host = fmt.Sprintf("%s:%d", endpointHost, defaultPort)
endpointUrl.Host = fmt.Sprintf("%s:%d", chosenEndpoint.Address, defaultPort)
} else {
endpointUrl.Host = endpointHost
endpointUrl.Host = chosenEndpoint.Address
}
var reqs []credential.Request
@@ -1028,9 +1033,9 @@ HostSourceIterationLoop:
expTime.Seconds += int64(t.GetSessionMaxSeconds())
sessionComposition := session.ComposedOf{
UserId: authResults.UserId,
HostId: chosenId.hostId,
HostId: chosenEndpoint.HostId,
TargetId: t.GetPublicId(),
HostSetId: chosenId.hostSetId,
HostSetId: chosenEndpoint.SetId,
AuthTokenId: authResults.AuthTokenId,
ScopeId: authResults.Scope.Id,
Endpoint: endpointUrl.String(),
@@ -1122,7 +1127,7 @@ HostSourceIterationLoop:
Type: t.GetType(),
Certificate: sess.Certificate,
PrivateKey: privKey,
HostId: chosenId.hostId,
HostId: chosenEndpoint.HostId,
Endpoint: endpointUrl.String(),
WorkerInfo: workers,
ConnectionLimit: t.GetSessionConnectionLimit(),
@@ -1141,8 +1146,8 @@ HostSourceIterationLoop:
Type: t.GetType(),
AuthorizationToken: string(encodedMarshaledSad),
UserId: authResults.UserId,
HostId: chosenId.hostId,
HostSetId: chosenId.hostSetId,
HostId: chosenEndpoint.HostId,
HostSetId: chosenEndpoint.SetId,
Endpoint: endpointUrl.String(),
Credentials: creds,
}
@@ -88,10 +88,13 @@ 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)
}
pluginHostRepoFn := func() (*plugin.Repository, error) {
return plugin.NewRepository(rw, rw, kms, map[string]plgpb.HostPluginServiceServer{})
}
credentialRepoFn := func() (*vault.Repository, error) {
return vault.NewRepository(rw, rw, kms, sche)
}
return targets.NewService(kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, staticHostRepoFn, credentialRepoFn)
return targets.NewService(context.Background(), kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, pluginHostRepoFn, staticHostRepoFn, credentialRepoFn)
}
func TestGet(t *testing.T) {
@@ -2586,6 +2589,33 @@ func TestAuthorizeSession(t *testing.T) {
return authtoken.NewRepository(rw, rw, kms)
}
plg := host.TestPlugin(t, conn, "test")
plgm := map[string]plgpb.HostPluginServiceServer{
plg.GetPublicId(): plugin.TestPluginServer{
ListHostsFn: func(_ context.Context, req *plgpb.ListHostsRequest) (*plgpb.ListHostsResponse, error) {
var setIds []string
for _, set := range req.GetSets() {
setIds = append(setIds, set.GetId())
}
return &plgpb.ListHostsResponse{Hosts: []*plgpb.ListHostsResponseHost{
{
SetIds: setIds,
ExternalId: "test",
IpAddresses: []string{"10.0.0.1", "192.168.0.1"},
},
{
SetIds: setIds,
ExternalId: "test2",
IpAddresses: []string{"10.1.1.1", "192.168.1.1"},
},
}}, nil
},
},
}
pluginHostRepoFn := func() (*plugin.Repository, error) {
return plugin.NewRepository(rw, rw, kms, plgm)
}
org, proj := iam.TestScopes(t, iamRepo)
at := authtoken.TestAuthToken(t, conn, kms, org.GetPublicId())
ctx := auth.NewVerifierContext(requests.NewRequestContext(context.Background()),
@@ -2603,21 +2633,16 @@ func TestAuthorizeSession(t *testing.T) {
_ = 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)
s, err := targets.NewService(ctx, kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, pluginHostRepoFn, 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})
shs := static.TestSets(t, conn, hc.GetPublicId(), 1)[0]
_ = static.TestSetMembers(t, conn, shs.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)
phc := plugin.TestCatalog(t, conn, proj.GetPublicId(), plg.GetPublicId())
phs := plugin.TestSet(t, conn, kms, phc, plgm, plugin.WithPreferredEndpoints([]string{"cidr:10.0.0.0/24"}))
v := vault.NewTestVaultServer(t)
v.MountPKI(t)
@@ -2638,95 +2663,135 @@ func TestAuthorizeSession(t *testing.T) {
}})
require.NoError(t, err)
_, err = s.AddTargetCredentialSources(ctx,
&pbs.AddTargetCredentialSourcesRequest{
Id: tar.GetPublicId(),
ApplicationCredentialSourceIds: []string{clsResp.GetItem().GetId()},
Version: apiTar.GetItem().GetVersion(),
cases := []struct {
name string
hostSourceId string
credSourceId string
wantedHostId string
wantedEndpoint string
}{
{
name: "static host",
hostSourceId: shs.GetPublicId(),
credSourceId: clsResp.GetItem().GetId(),
wantedHostId: h.GetPublicId(),
wantedEndpoint: h.GetAddress(),
},
{
name: "plugin host",
hostSourceId: phs.GetPublicId(),
credSourceId: clsResp.GetItem().GetId(),
wantedHostId: "?",
wantedEndpoint: "10.0.0.1",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
tar := target.TestTcpTarget(t, conn, proj.GetPublicId(), tc.name)
apiTar, err := s.AddTargetHostSets(ctx, &pbs.AddTargetHostSetsRequest{
Id: tar.GetPublicId(),
Version: tar.GetVersion(),
HostSetIds: []string{tc.hostSourceId},
})
require.NoError(t, err)
_, err = s.AddTargetCredentialSources(ctx,
&pbs.AddTargetCredentialSourcesRequest{
Id: tar.GetPublicId(),
ApplicationCredentialSourceIds: []string{clsResp.GetItem().GetId()},
Version: apiTar.GetItem().GetVersion(),
})
require.NoError(t, err)
// Tell our DB that there is a worker ready to serve the data
workerService := workers.NewWorkerServiceServer(serversRepoFn, sessionRepoFn, &sync.Map{}, kms)
_, err = workerService.Status(ctx, &spbs.StatusRequest{
Worker: &spb.Server{
PrivateId: "testworker",
Address: "localhost:8457",
},
})
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")
wantedHostId := tc.wantedHostId
if tc.wantedHostId == "?" {
wantedHostId = asRes2.GetItem().GetHostId()
}
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: tc.hostSourceId,
HostId: wantedHostId,
Type: "tcp",
Endpoint: fmt.Sprintf("tcp://%s", tc.wantedEndpoint),
Credentials: []*pb.SessionCredential{{
CredentialLibrary: &pb.CredentialLibrary{
Id: clsResp.GetItem().GetId(),
Name: clsResp.GetItem().GetName().GetValue(),
Description: clsResp.GetItem().GetDescription().GetValue(),
CredentialStoreId: store.GetPublicId(),
Type: vault.Subtype.String(),
},
CredentialSource: &pb.CredentialSource{
Id: clsResp.GetItem().GetId(),
Name: clsResp.GetItem().GetName().GetValue(),
Description: clsResp.GetItem().GetDescription().GetValue(),
CredentialStoreId: store.GetPublicId(),
Type: vault.Subtype.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",
}
got := asRes1.GetItem()
require.Len(t, got.GetCredentials(), 1)
gotCred := got.Credentials[0]
require.NotNil(t, gotCred.Secret)
assert.NotEmpty(t, gotCred.Secret.Raw)
dSec := decodeJsonSecret(t, gotCred.Secret.Raw)
require.NoError(t, err)
require.Equal(t, dSec, gotCred.Secret.Decoded.AsMap())
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 = nil
got.AuthorizationToken, got.SessionId, got.CreatedTime = "", "", nil
assert.Empty(t, cmp.Diff(got, want, protocmp.Transform()))
})
require.NoError(t, err)
// Tell our DB that there is a worker ready to serve the data
workerService := workers.NewWorkerServiceServer(serversRepoFn, sessionRepoFn, &sync.Map{}, kms)
_, err = workerService.Status(ctx, &spbs.StatusRequest{
Worker: &spb.Server{
PrivateId: "testworker",
Address: "localhost:8457",
},
})
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: vault.Subtype.String(),
},
CredentialSource: &pb.CredentialSource{
Id: clsResp.GetItem().GetId(),
Name: clsResp.GetItem().GetName().GetValue(),
Description: clsResp.GetItem().GetDescription().GetValue(),
CredentialStoreId: store.GetPublicId(),
Type: vault.Subtype.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",
}
got := asRes1.GetItem()
require.Len(t, got.GetCredentials(), 1)
gotCred := got.Credentials[0]
require.NotNil(t, gotCred.Secret)
assert.NotEmpty(t, gotCred.Secret.Raw)
dSec := decodeJsonSecret(t, gotCred.Secret.Raw)
require.NoError(t, err)
require.Equal(t, dSec, gotCred.Secret.Decoded.AsMap())
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 = nil
got.AuthorizationToken, got.SessionId, got.CreatedTime = "", "", nil
assert.Empty(t, cmp.Diff(got, want, protocmp.Transform()))
}
func TestAuthorizeSession_Errors(t *testing.T) {
ctx := context.Background()
conn, _ := db.TestSetup(t, "postgres")
rw := db.New(conn)
wrapper := db.TestWrapper(t)
@@ -2749,6 +2814,9 @@ func TestAuthorizeSession_Errors(t *testing.T) {
staticHostRepoFn := func() (*static.Repository, error) {
return static.NewRepository(rw, rw, kms)
}
pluginHostRepoFn := func() (*plugin.Repository, error) {
return plugin.NewRepository(rw, rw, kms, map[string]plgpb.HostPluginServiceServer{})
}
credentialRepoFn := func() (*vault.Repository, error) {
return vault.NewRepository(rw, rw, kms, sche)
}
@@ -2757,12 +2825,12 @@ func TestAuthorizeSession_Errors(t *testing.T) {
}
org, proj := iam.TestScopes(t, iamRepo)
s, err := targets.NewService(kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, staticHostRepoFn, credentialRepoFn)
s, err := targets.NewService(ctx, kms, repoFn, iamRepoFn, serversRepoFn, sessionRepoFn, pluginHostRepoFn, 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()),
ctx = auth.NewVerifierContext(requests.NewRequestContext(context.Background()),
iamRepoFn,
atRepoFn,
serversRepoFn,