2020-09-01 15:05:46 -07:00
// Copyright (c) HashiCorp, Inc.
2022-07-19 15:16:24 -07:00
// SPDX-License-Identifier: BUSL-1.1
2023-02-02 17:15:17 -08:00
2021-11-04 11:44:22 -04:00
package tcp_test
2020-09-01 15:05:46 -07:00
import (
"context"
2022-10-27 09:01:05 -04:00
"crypto/x509"
2021-06-22 22:26:26 -04:00
"encoding/base64"
"encoding/json"
2022-10-27 09:01:05 -04:00
"encoding/pem"
2020-09-23 08:10:27 -07:00
"errors"
2020-09-01 15:05:46 -07:00
"fmt"
2021-06-22 22:26:26 -04:00
"path"
2023-11-24 17:27:15 -08:00
"slices"
2020-09-01 15:05:46 -07:00
"strings"
2022-11-10 13:14:57 -05:00
"sync/atomic"
2020-09-01 15:05:46 -07:00
"testing"
"github.com/google/go-cmp/cmp"
2023-10-31 13:44:17 +00:00
"github.com/google/go-cmp/cmp/cmpopts"
2022-10-28 15:52:06 -04:00
"github.com/hashicorp/boundary/globals"
2024-02-01 08:58:56 -08:00
talias "github.com/hashicorp/boundary/internal/alias/target"
2023-03-15 11:40:40 -04:00
"github.com/hashicorp/boundary/internal/auth/ldap"
2022-10-27 09:01:05 -04:00
"github.com/hashicorp/boundary/internal/auth/oidc"
"github.com/hashicorp/boundary/internal/auth/password"
2021-06-22 22:26:26 -04:00
"github.com/hashicorp/boundary/internal/authtoken"
2021-10-26 09:57:22 -04:00
"github.com/hashicorp/boundary/internal/credential"
2022-06-08 13:51:56 -07:00
credstatic "github.com/hashicorp/boundary/internal/credential/static"
2021-06-22 22:26:26 -04:00
"github.com/hashicorp/boundary/internal/credential/vault"
2022-05-09 12:45:10 -07:00
"github.com/hashicorp/boundary/internal/daemon/controller/auth"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers"
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/credentiallibraries"
2022-06-09 15:35:55 -07:00
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/credentials"
2022-05-09 12:45:10 -07:00
"github.com/hashicorp/boundary/internal/daemon/controller/handlers/targets"
2020-09-01 15:05:46 -07:00
"github.com/hashicorp/boundary/internal/db"
2024-04-06 13:48:47 -07:00
"github.com/hashicorp/boundary/internal/event"
2020-09-01 15:05:46 -07:00
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
2021-10-19 17:21:41 -04:00
authpb "github.com/hashicorp/boundary/internal/gen/controller/auth"
2023-04-24 19:27:41 -04:00
hostplugin "github.com/hashicorp/boundary/internal/host/plugin"
2020-09-01 15:05:46 -07:00
"github.com/hashicorp/boundary/internal/host/static"
"github.com/hashicorp/boundary/internal/iam"
"github.com/hashicorp/boundary/internal/kms"
2023-04-24 19:27:41 -04:00
"github.com/hashicorp/boundary/internal/plugin"
2023-04-19 11:27:00 -07:00
"github.com/hashicorp/boundary/internal/plugin/loopback"
2021-06-22 22:26:26 -04:00
"github.com/hashicorp/boundary/internal/requests"
"github.com/hashicorp/boundary/internal/scheduler"
2022-06-20 18:20:17 -07:00
"github.com/hashicorp/boundary/internal/server"
2020-09-19 00:18:17 -04:00
"github.com/hashicorp/boundary/internal/session"
2020-09-01 15:05:46 -07:00
"github.com/hashicorp/boundary/internal/target"
2021-09-29 13:13:49 -04:00
"github.com/hashicorp/boundary/internal/target/tcp"
2023-11-24 17:27:15 -08:00
"github.com/hashicorp/boundary/internal/target/tcp/store"
2020-09-01 15:05:46 -07:00
"github.com/hashicorp/boundary/internal/types/scope"
2022-06-09 15:35:55 -07:00
credlibpb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/credentiallibraries"
credpb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/credentials"
2021-08-26 10:44:41 -04:00
"github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/scopes"
pb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/targets"
2021-09-21 09:18:49 -07:00
plgpb "github.com/hashicorp/boundary/sdk/pbs/plugin"
2022-03-16 17:04:07 -04:00
wrapping "github.com/hashicorp/go-kms-wrapping/v2"
2024-04-06 13:48:47 -07:00
"github.com/hashicorp/go-uuid"
2020-09-01 15:05:46 -07:00
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
2022-07-19 10:31:53 -07:00
"golang.org/x/crypto/ssh/testdata"
2020-09-01 15:05:46 -07:00
"google.golang.org/genproto/protobuf/field_mask"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/testing/protocmp"
2020-09-15 15:20:49 -04:00
"google.golang.org/protobuf/types/known/structpb"
2021-04-23 09:13:37 -05:00
"google.golang.org/protobuf/types/known/timestamppb"
2020-09-01 15:05:46 -07:00
"google.golang.org/protobuf/types/known/wrapperspb"
2021-11-04 11:44:22 -04:00
2022-05-09 12:45:10 -07:00
_ "github.com/hashicorp/boundary/internal/daemon/controller/handlers/targets/tcp"
2020-09-01 15:05:46 -07:00
)
2021-06-22 22:26:26 -04:00
var testAuthorizedActions = [] string {
"no-op" ,
"read" ,
"update" ,
"delete" ,
2021-12-15 10:06:35 -08:00
"add-host-sources" ,
"set-host-sources" ,
"remove-host-sources" ,
2021-07-27 12:48:36 -04:00
"add-credential-sources" ,
"set-credential-sources" ,
"remove-credential-sources" ,
2021-06-22 22:26:26 -04:00
"authorize-session" ,
}
2021-04-23 09:13:37 -05:00
2023-02-16 17:34:25 -08:00
// Create a variable that we can overwrite in enterprise tests
var expectedDeprecatedWorkerFilterError = "Use egress_worker_filter instead"
2022-06-15 08:56:24 -07:00
func testService ( t * testing . T , ctx context . Context , conn * db . DB , kms * kms . Kms , wrapper wrapping . Wrapper ) ( targets . Service , error ) {
2020-09-19 00:18:17 -04:00
rw := db . New ( conn )
2021-06-22 22:26:26 -04:00
sche := scheduler . TestScheduler ( t , conn , wrapper )
2025-01-09 10:26:37 -08:00
workerRPCGracePeriod := new ( atomic . Int64 )
workerRPCGracePeriod . Store ( int64 ( server . DefaultLiveness ))
2022-08-23 17:27:56 +01:00
repoFn := func ( o ... target . Option ) ( * target . Repository , error ) {
2022-08-23 18:44:10 +01:00
return target . NewRepository ( ctx , rw , rw , kms , o ... )
2020-09-19 00:18:17 -04:00
}
iamRepoFn := func () ( * iam . Repository , error ) {
return iam . TestRepo ( t , conn , wrapper ), nil
}
2022-06-20 18:20:17 -07:00
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2020-09-19 00:18:17 -04:00
}
2022-08-09 12:43:38 +00:00
sessionRepoFn := func ( opts ... session . Option ) ( * session . Repository , error ) {
2022-08-24 13:22:03 +00:00
return session . NewRepository ( ctx , rw , rw , kms , opts ... )
2020-09-19 00:18:17 -04:00
}
staticHostRepoFn := func () ( * static . Repository , error ) {
2023-06-06 17:09:08 -04:00
return static . NewRepository ( ctx , rw , rw , kms )
2020-09-19 00:18:17 -04:00
}
2023-04-24 19:27:41 -04:00
pluginHostRepoFn := func () ( * hostplugin . Repository , error ) {
2023-06-06 17:09:08 -04:00
return hostplugin . NewRepository ( ctx , rw , rw , kms , sche , map [ string ] plgpb . HostPluginServiceClient {})
2021-09-26 08:17:21 -07:00
}
2022-06-09 15:35:55 -07:00
vaultCredRepoFn := func () ( * vault . Repository , error ) {
2023-06-06 17:09:08 -04:00
return vault . NewRepository ( ctx , rw , rw , kms , sche )
2021-06-22 22:26:26 -04:00
}
2022-06-09 15:35:55 -07:00
staticCredRepoFn := func () ( * credstatic . Repository , error ) {
return credstatic . NewRepository ( context . Background (), rw , rw , kms )
}
2024-02-01 08:58:56 -08:00
targetAliasRepoFn := func () ( * talias . Repository , error ) {
return talias . NewRepository ( ctx , rw , rw , kms )
}
2025-01-09 10:26:37 -08:00
return targets . NewService ( ctx , kms , repoFn , iamRepoFn , serversRepoFn , sessionRepoFn , pluginHostRepoFn , staticHostRepoFn , vaultCredRepoFn , staticCredRepoFn , targetAliasRepoFn , nil , workerRPCGracePeriod , 1000 , nil )
2020-09-19 00:18:17 -04:00
}
2020-09-01 15:05:46 -07:00
func TestGet ( t * testing . T ) {
t . Parallel ()
2023-06-06 17:09:08 -04:00
ctx := context . Background ()
2020-09-01 15:05:46 -07:00
conn , _ := db . TestSetup ( t , "postgres" )
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
2022-07-29 17:24:39 +00:00
rw := db . New ( conn )
2021-03-25 03:15:43 -04:00
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
2022-07-29 17:24:39 +00:00
tokenRepoFn := func () ( * authtoken . Repository , error ) {
2023-06-06 17:09:08 -04:00
return authtoken . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
2021-03-25 03:15:43 -04:00
o , proj := iam . TestScopes ( t , iamRepo )
2022-07-29 17:24:39 +00:00
at := authtoken . TestAuthToken ( t , conn , kms , o . GetPublicId ())
r := iam . TestRole ( t , conn , proj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2020-09-01 15:05:46 -07:00
hc := static . TestCatalogs ( t , conn , proj . GetPublicId (), 1 )[ 0 ]
hs := static . TestSets ( t , conn , hc . GetPublicId (), 2 )
2021-11-04 11:44:22 -04:00
tar := tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "test" , target . WithHostSources ([] string { hs [ 0 ]. GetPublicId (), hs [ 1 ]. GetPublicId ()}))
2020-09-01 15:05:46 -07:00
2022-12-06 12:33:28 -08:00
tarAddr := tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "test address" , target . WithAddress ( "8.8.8.8" ))
2024-03-12 13:57:47 -07:00
al := talias . TestAlias ( t , rw , "test.alias" , talias . WithDestinationId ( tar . GetPublicId ()), talias . WithHostId ( "hsht_1234567890" ))
2024-02-01 08:58:56 -08:00
2024-02-01 14:36:58 -05:00
pAlias := & pb . Alias {
Id : al . GetPublicId (),
Value : al . GetValue (),
}
2020-09-01 15:05:46 -07:00
pTar := & pb . Target {
2020-09-19 14:01:49 -04:00
Id : tar . GetPublicId (),
ScopeId : proj . GetPublicId (),
Name : wrapperspb . String ( "test" ),
2021-11-04 11:44:22 -04:00
CreatedTime : tar . GetCreateTime (). GetTimestamp (),
UpdatedTime : tar . GetUpdateTime (). GetTimestamp (),
2021-03-25 03:15:43 -04:00
Scope : & scopes . ScopeInfo { Id : proj . GetPublicId (), Type : scope . Project . String (), ParentScopeId : o . GetPublicId ()},
2023-11-02 16:03:47 -04:00
Type : tcp . Subtype . String (),
2021-07-30 08:48:03 -04:00
HostSourceIds : [] string { hs [ 0 ]. GetPublicId (), hs [ 1 ]. GetPublicId ()},
2022-04-13 16:27:48 -04:00
Attrs : & pb . Target_TcpTargetAttributes {},
2020-09-20 15:53:49 -04:00
SessionMaxSeconds : wrapperspb . UInt32 ( 28800 ),
2022-07-06 09:02:56 -07:00
SessionConnectionLimit : wrapperspb . Int32 ( - 1 ),
2021-04-23 09:13:37 -05:00
AuthorizedActions : testAuthorizedActions ,
2022-12-06 12:33:28 -08:00
Address : & wrapperspb . StringValue {},
2024-02-01 14:36:58 -05:00
Aliases : [] * pb . Alias { pAlias },
2020-09-01 15:05:46 -07:00
}
for _ , ihs := range hs {
2021-07-30 08:48:03 -04:00
pTar . HostSources = append ( pTar . HostSources , & pb . HostSource { Id : ihs . GetPublicId (), HostCatalogId : ihs . GetCatalogId ()})
2020-09-01 15:05:46 -07:00
}
2022-12-06 12:33:28 -08:00
pTarAddr := & pb . Target {
Id : tarAddr . GetPublicId (),
ScopeId : proj . GetPublicId (),
Name : wrapperspb . String ( "test address" ),
CreatedTime : tarAddr . GetCreateTime (). GetTimestamp (),
UpdatedTime : tarAddr . GetUpdateTime (). GetTimestamp (),
Scope : & scopes . ScopeInfo { Id : proj . GetPublicId (), Type : scope . Project . String (), ParentScopeId : o . GetPublicId ()},
2023-11-02 16:03:47 -04:00
Type : tcp . Subtype . String (),
2022-12-06 12:33:28 -08:00
Attrs : & pb . Target_TcpTargetAttributes {},
SessionMaxSeconds : wrapperspb . UInt32 ( 28800 ),
SessionConnectionLimit : wrapperspb . Int32 ( - 1 ),
AuthorizedActions : testAuthorizedActions ,
Address : & wrapperspb . StringValue { Value : "8.8.8.8" },
}
2020-09-01 15:05:46 -07:00
cases := [] struct {
2020-09-23 08:10:27 -07:00
name string
req * pbs . GetTargetRequest
res * pbs . GetTargetResponse
err error
2020-09-01 15:05:46 -07:00
}{
{
2020-09-23 08:10:27 -07:00
name : "Get an Existing Target" ,
req : & pbs . GetTargetRequest { Id : tar . GetPublicId ()},
res : & pbs . GetTargetResponse { Item : pTar },
2020-09-01 15:05:46 -07:00
},
2022-12-06 12:33:28 -08:00
{
name : "Get an Existing Target w/ address" ,
req : & pbs . GetTargetRequest { Id : tarAddr . GetPublicId ()},
res : & pbs . GetTargetResponse { Item : pTarAddr },
},
2020-09-01 15:05:46 -07:00
{
2020-09-23 08:10:27 -07:00
name : "Get a non existing Target" ,
2023-03-10 15:06:39 -05:00
req : & pbs . GetTargetRequest { Id : globals . TcpTargetPrefix + "_DoesntExis" },
2020-09-23 08:10:27 -07:00
res : nil ,
err : handlers . ApiErrorWithCode ( codes . NotFound ),
2020-09-01 15:05:46 -07:00
},
{
2020-09-23 08:10:27 -07:00
name : "Wrong id prefix" ,
req : & pbs . GetTargetRequest { Id : "j_1234567890" },
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
{
2020-09-23 08:10:27 -07:00
name : "space in id" ,
2023-03-10 15:06:39 -05:00
req : & pbs . GetTargetRequest { Id : globals . TcpTargetPrefix + "_1 23456789" },
2020-09-23 08:10:27 -07:00
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
}
for _ , tc := range cases {
t . Run ( tc . name , func ( t * testing . T ) {
2020-09-23 08:10:27 -07:00
assert , require := assert . New ( t ), require . New ( t )
2020-09-01 15:05:46 -07:00
2023-06-06 17:09:08 -04:00
s , err := testService ( t , ctx , conn , kms , wrapper )
2020-09-23 08:10:27 -07:00
require . NoError ( err , "Couldn't create a new host set service." )
2020-09-01 15:05:46 -07:00
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx := auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
got , gErr := s . GetTarget ( ctx , tc . req )
2020-09-23 08:10:27 -07:00
if tc . err != nil {
require . Error ( gErr )
assert . True ( errors . Is ( gErr , tc . err ), "GetTarget(%+v) got error %v, wanted %v" , tc . req , gErr , tc . err )
2024-02-01 08:58:56 -08:00
return
2020-09-23 08:10:27 -07:00
}
2024-02-01 08:58:56 -08:00
require . NoError ( gErr )
2020-09-01 15:05:46 -07:00
if tc . res != nil {
tc . res . Item . Version = 1
}
2023-10-31 13:44:17 +00:00
assert . Empty ( cmp . Diff (
got ,
tc . res ,
protocmp . Transform (),
cmpopts . SortSlices ( func ( a , b string ) bool {
return a < b
}),
), "GetTarget(%q) got response %q, wanted %q" , tc . req , got , tc . res )
2020-09-01 15:05:46 -07:00
})
}
}
func TestList ( t * testing . T ) {
2023-08-28 15:08:20 -07:00
t . Parallel ()
2023-06-06 17:09:08 -04:00
ctx := context . Background ()
2020-09-01 15:05:46 -07:00
conn , _ := db . TestSetup ( t , "postgres" )
2023-11-24 17:27:15 -08:00
sqlDB , err := conn . SqlDB ( ctx )
require . NoError ( t , err )
2020-09-01 15:05:46 -07:00
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
2022-07-29 17:24:39 +00:00
rw := db . New ( conn )
2021-01-25 19:37:40 -05:00
iamRepo := iam . TestRepo ( t , conn , wrapper )
2021-03-25 03:15:43 -04:00
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
2022-07-29 17:24:39 +00:00
tokenRepoFn := func () ( * authtoken . Repository , error ) {
2023-06-06 17:09:08 -04:00
return authtoken . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
2021-03-25 03:15:43 -04:00
2021-01-25 19:37:40 -05:00
_ , projNoTar := iam . TestScopes ( t , iamRepo )
2021-03-25 03:15:43 -04:00
org , proj := iam . TestScopes ( t , iamRepo )
2022-07-29 17:24:39 +00:00
at := authtoken . TestAuthToken ( t , conn , kms , org . GetPublicId ())
r := iam . TestRole ( t , conn , proj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2022-07-29 17:24:39 +00:00
ar := iam . TestRole ( t , conn , proj . GetPublicId ())
2022-10-28 15:52:06 -04:00
_ = iam . TestUserRole ( t , conn , ar . GetPublicId (), globals . AnonymousUserId )
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , ar . GetPublicId (), "ids=*;type=target;actions=*" )
2022-07-29 17:24:39 +00:00
2021-03-25 03:15:43 -04:00
otherOrg , otherProj := iam . TestScopes ( t , iamRepo )
2022-07-29 17:24:39 +00:00
r = iam . TestRole ( t , conn , otherProj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2020-09-01 15:05:46 -07:00
hc := static . TestCatalogs ( t , conn , proj . GetPublicId (), 1 )[ 0 ]
2021-01-25 19:37:40 -05:00
otherHc := static . TestCatalogs ( t , conn , otherProj . GetPublicId (), 1 )[ 0 ]
2020-09-01 15:05:46 -07:00
hss := static . TestSets ( t , conn , hc . GetPublicId (), 2 )
2021-01-25 19:37:40 -05:00
otherHss := static . TestSets ( t , conn , otherHc . GetPublicId (), 2 )
2020-09-01 15:05:46 -07:00
var wantTars [] * pb . Target
2021-01-25 19:37:40 -05:00
var totalTars [] * pb . Target
2020-09-01 15:05:46 -07:00
for i := 0 ; i < 5 ; i ++ {
name := fmt . Sprintf ( "tar%d" , i )
2021-11-04 11:44:22 -04:00
tar := tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), name , target . WithHostSources ([] string { hss [ 0 ]. GetPublicId (), hss [ 1 ]. GetPublicId ()}))
2020-09-01 15:05:46 -07:00
wantTars = append ( wantTars , & pb . Target {
2020-09-19 14:01:49 -04:00
Id : tar . GetPublicId (),
ScopeId : proj . GetPublicId (),
Name : wrapperspb . String ( name ),
2021-03-25 03:15:43 -04:00
Scope : & scopes . ScopeInfo { Id : proj . GetPublicId (), Type : scope . Project . String (), ParentScopeId : org . GetPublicId ()},
2020-09-19 14:01:49 -04:00
CreatedTime : tar . GetCreateTime (). GetTimestamp (),
UpdatedTime : tar . GetUpdateTime (). GetTimestamp (),
Version : tar . GetVersion (),
2023-11-02 16:03:47 -04:00
Type : tcp . Subtype . String (),
2022-04-13 16:27:48 -04:00
Attrs : & pb . Target_TcpTargetAttributes {},
2020-09-20 15:53:49 -04:00
SessionMaxSeconds : wrapperspb . UInt32 ( 28800 ),
2022-07-06 09:02:56 -07:00
SessionConnectionLimit : wrapperspb . Int32 ( - 1 ),
2021-04-23 09:13:37 -05:00
AuthorizedActions : testAuthorizedActions ,
2022-12-06 12:33:28 -08:00
Address : & wrapperspb . StringValue {},
2020-09-01 15:05:46 -07:00
})
2021-01-25 19:37:40 -05:00
totalTars = append ( totalTars , wantTars [ i ])
2021-11-04 11:44:22 -04:00
tar = tcp . TestTarget ( ctx , t , conn , otherProj . GetPublicId (), name , target . WithHostSources ([] string { otherHss [ 0 ]. GetPublicId (), otherHss [ 1 ]. GetPublicId ()}))
2021-01-25 19:37:40 -05:00
totalTars = append ( totalTars , & pb . Target {
Id : tar . GetPublicId (),
ScopeId : otherProj . GetPublicId (),
Name : wrapperspb . String ( name ),
2021-03-25 03:15:43 -04:00
Scope : & scopes . ScopeInfo { Id : otherProj . GetPublicId (), Type : scope . Project . String (), ParentScopeId : otherOrg . GetPublicId ()},
2021-01-25 19:37:40 -05:00
CreatedTime : tar . GetCreateTime (). GetTimestamp (),
UpdatedTime : tar . GetUpdateTime (). GetTimestamp (),
Version : tar . GetVersion (),
2023-11-02 16:03:47 -04:00
Type : tcp . Subtype . String (),
2022-04-13 16:27:48 -04:00
Attrs : & pb . Target_TcpTargetAttributes {},
2021-01-25 19:37:40 -05:00
SessionMaxSeconds : wrapperspb . UInt32 ( 28800 ),
2022-07-06 09:02:56 -07:00
SessionConnectionLimit : wrapperspb . Int32 ( - 1 ),
2021-04-23 09:13:37 -05:00
AuthorizedActions : testAuthorizedActions ,
2022-12-06 12:33:28 -08:00
Address : & wrapperspb . StringValue {},
2021-01-25 19:37:40 -05:00
})
2020-09-01 15:05:46 -07:00
}
2023-11-24 17:27:15 -08:00
// Run analyze to update postgres estimates
_ , err = sqlDB . ExecContext ( ctx , "analyze" )
require . NoError ( t , err )
// Reverse slices since response is ordered by created_time descending (newest first)
slices . Reverse ( wantTars )
slices . Reverse ( totalTars )
2020-09-01 15:05:46 -07:00
cases := [] struct {
2021-01-25 19:37:40 -05:00
name string
req * pbs . ListTargetsRequest
res * pbs . ListTargetsResponse
err error
2020-09-01 15:05:46 -07:00
}{
{
2021-01-25 19:37:40 -05:00
name : "List Many Targets" ,
req : & pbs . ListTargetsRequest { ScopeId : proj . GetPublicId ()},
2023-11-24 17:27:15 -08:00
res : & pbs . ListTargetsResponse {
Items : wantTars ,
ResponseType : "complete" ,
SortBy : "created_time" ,
SortDir : "desc" ,
EstItemCount : 5 ,
},
2021-01-25 19:37:40 -05:00
},
{
name : "List No Targets" ,
req : & pbs . ListTargetsRequest { ScopeId : projNoTar . GetPublicId ()},
res : & pbs . ListTargetsResponse {},
2020-09-01 15:05:46 -07:00
},
{
2021-01-25 19:37:40 -05:00
name : "List Targets Recursively" ,
req : & pbs . ListTargetsRequest { ScopeId : scope . Global . String (), Recursive : true },
2023-11-24 17:27:15 -08:00
res : & pbs . ListTargetsResponse {
Items : totalTars ,
ResponseType : "complete" ,
SortBy : "created_time" ,
SortDir : "desc" ,
EstItemCount : 10 ,
},
2020-09-01 15:05:46 -07:00
},
2023-10-24 09:41:11 -07:00
{
name : "Paginate listing" ,
req : & pbs . ListTargetsRequest { ScopeId : scope . Global . String (), Recursive : true , PageSize : 2 },
2023-11-24 17:27:15 -08:00
res : & pbs . ListTargetsResponse {
Items : totalTars [: 2 ],
ResponseType : "delta" ,
SortBy : "created_time" ,
SortDir : "desc" ,
EstItemCount : 10 ,
},
2023-10-24 09:41:11 -07:00
},
2021-02-22 10:09:25 -07:00
{
name : "Filter To Many Targets" ,
req : & pbs . ListTargetsRequest { ScopeId : scope . Global . String (), Recursive : true , Filter : fmt . Sprintf ( `"/item/scope/id"==%q` , proj . GetPublicId ())},
2023-11-24 17:27:15 -08:00
res : & pbs . ListTargetsResponse {
Items : wantTars ,
ResponseType : "complete" ,
SortBy : "created_time" ,
SortDir : "desc" ,
EstItemCount : 5 ,
},
2021-02-22 10:09:25 -07:00
},
{
name : "Filter To No Targets" ,
req : & pbs . ListTargetsRequest { ScopeId : proj . GetPublicId (), Filter : `"/item/id"=="doesnt match"` },
2023-11-24 17:27:15 -08:00
res : & pbs . ListTargetsResponse {
ResponseType : "complete" ,
SortBy : "created_time" ,
SortDir : "desc" ,
},
2021-02-22 10:09:25 -07:00
},
{
name : "Filter Bad Format" ,
req : & pbs . ListTargetsRequest { ScopeId : proj . GetPublicId (), Filter : `"/badformat/"` },
err : handlers . InvalidArgumentErrorf ( "bad format" , nil ),
},
2020-09-01 15:05:46 -07:00
}
for _ , tc := range cases {
t . Run ( tc . name , func ( t * testing . T ) {
assert , require := assert . New ( t ), require . New ( t )
2022-06-15 08:56:24 -07:00
s , err := testService ( t , context . Background (), conn , kms , wrapper )
2020-09-01 15:05:46 -07:00
require . NoError ( err , "Couldn't create new host set service." )
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx := auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
got , gErr := s . ListTargets ( ctx , tc . req )
2020-09-23 08:10:27 -07:00
if tc . err != nil {
require . Error ( gErr )
2021-01-25 19:37:40 -05:00
assert . True ( errors . Is ( gErr , tc . err ), "ListTargets(%q) got error %v, wanted %v" , tc . req . GetScopeId (), gErr , tc . err )
2021-05-04 19:57:35 -05:00
return
2020-09-23 08:10:27 -07:00
}
2021-05-04 19:57:35 -05:00
require . NoError ( gErr )
2021-11-02 15:38:37 -04:00
assert . Equal ( len ( tc . res . Items ), len ( got . Items ))
wantById := make ( map [ string ] * pb . Target , len ( tc . res . Items ))
for _ , t := range tc . res . Items {
wantById [ t . Id ] = t
}
for _ , t := range got . Items {
want , ok := wantById [ t . Id ]
assert . True ( ok , "Got unexpected target with id: %s" , t . Id )
2023-10-31 13:44:17 +00:00
assert . Empty ( cmp . Diff (
t ,
want ,
protocmp . Transform (),
cmpopts . SortSlices ( func ( a , b string ) bool {
return a < b
}),
), "got %v, wanted %v" , t , want )
2021-11-02 15:38:37 -04:00
}
2021-05-04 19:57:35 -05:00
// Test with anon user
2022-07-29 17:24:39 +00:00
requestInfo = authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeUnknown ),
}
requestContext = context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx = auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
_ , gErr = s . ListTargets ( ctx , tc . req )
require . Error ( gErr )
// For now, due to how recursive checks the additional scopes,
// it gets a 403 while a non-recursive expects a 401
if tc . req . GetRecursive () {
assert . ErrorIs ( gErr , handlers . ForbiddenError ())
} else {
assert . ErrorIs ( gErr , handlers . UnauthenticatedError ())
2021-05-04 19:57:35 -05:00
}
2020-09-01 15:05:46 -07:00
})
}
}
2024-09-17 10:07:43 -04:00
func TestListGrantScopes ( t * testing . T ) {
t . Parallel ()
2023-10-24 09:41:11 -07:00
ctx := context . Background ()
conn , _ := db . TestSetup ( t , "postgres" )
sqlDB , err := conn . SqlDB ( ctx )
require . NoError ( t , err )
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
rw := db . New ( conn )
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
tokenRepoFn := func () ( * authtoken . Repository , error ) {
return authtoken . NewRepository ( ctx , rw , rw , kms )
}
serversRepoFn := func () ( * server . Repository , error ) {
return server . NewRepository ( ctx , rw , rw , kms )
}
2024-09-17 10:07:43 -04:00
at := authtoken . TestAuthToken ( t , conn , kms , scope . Global . String ())
2023-10-24 09:41:11 -07:00
2024-09-17 10:07:43 -04:00
var projects [] * iam . Scope
org1 , proj1 := iam . TestScopes ( t , iamRepo )
projects = append ( projects , proj1 )
org2 , proj2 := iam . TestScopes ( t , iamRepo )
projects = append ( projects , proj2 )
var totalTars [] * pb . Target
for i , proj := range projects {
for j := 0 ; j < 5 ; j ++ {
name := fmt . Sprintf ( "tar-%d-%d" , i , j )
tar := tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), name , target . WithAddress ( fmt . Sprintf ( "1.1.%d.%d" , i , j )))
totalTars = append ( totalTars , & pb . Target {
Id : tar . GetPublicId (),
ScopeId : proj . GetPublicId (),
Name : wrapperspb . String ( name ),
Scope : & scopes . ScopeInfo { Id : proj . GetPublicId (), Type : scope . Project . String (), ParentScopeId : proj . ParentId },
CreatedTime : tar . GetCreateTime (). GetTimestamp (),
UpdatedTime : tar . GetUpdateTime (). GetTimestamp (),
Version : tar . GetVersion (),
Type : tcp . Subtype . String (),
Attrs : & pb . Target_TcpTargetAttributes {},
SessionMaxSeconds : wrapperspb . UInt32 ( 28800 ),
SessionConnectionLimit : wrapperspb . Int32 ( - 1 ),
AuthorizedActions : testAuthorizedActions ,
Address : & wrapperspb . StringValue { Value : fmt . Sprintf ( "1.1.%d.%d" , i , j )},
})
}
2023-10-24 09:41:11 -07:00
}
// Run analyze to update postgres estimates
_ , err = sqlDB . ExecContext ( ctx , "analyze" )
require . NoError ( t , err )
2024-09-17 10:07:43 -04:00
_ = org1
_ = org2
2023-10-24 09:41:11 -07:00
2024-09-17 10:07:43 -04:00
cases := [] struct {
name string
pageSize uint32
setupFunc func ( t * testing . T )
res * pbs . ListTargetsResponse
err error
}{
{
name : "global-with-direct-grants-wildcard" ,
setupFunc : func ( t * testing . T ) {
globalRole := iam . TestRole ( t , conn , scope . Global . String (), iam . WithGrantScopeIds ([] string { proj1 . GetPublicId (), proj2 . GetPublicId ()}))
_ = iam . TestUserRole ( t , conn , globalRole . GetPublicId (), at . GetIamUserId ())
_ = iam . TestRoleGrant ( t , conn , globalRole . GetPublicId (), "ids=*;type=*;actions=*" )
},
res : & pbs . ListTargetsResponse {
Items : totalTars ,
ResponseType : "complete" ,
2023-11-24 17:27:15 -08:00
SortBy : "created_time" ,
SortDir : "desc" ,
2023-10-24 09:41:11 -07:00
EstItemCount : 10 ,
},
2024-09-17 10:07:43 -04:00
},
{
name : "global-with-direct-grants-non-wildcard" ,
setupFunc : func ( t * testing . T ) {
globalRole := iam . TestRole ( t , conn , scope . Global . String (), iam . WithGrantScopeIds ([] string { proj1 . GetPublicId (), proj2 . GetPublicId ()}))
_ = iam . TestUserRole ( t , conn , globalRole . GetPublicId (), at . GetIamUserId ())
_ = iam . TestRoleGrant ( t , conn , globalRole . GetPublicId (), "ids=*;type=target;actions=list" )
_ = iam . TestRoleGrant ( t , conn , globalRole . GetPublicId (), fmt . Sprintf ( "ids=%s,%s;actions=*" , totalTars [ 0 ]. Id , totalTars [ 1 ]. Id ))
},
res : & pbs . ListTargetsResponse {
Items : totalTars [ 0 : 2 ],
ResponseType : "complete" ,
2023-11-24 17:27:15 -08:00
SortBy : "created_time" ,
SortDir : "desc" ,
2024-09-17 10:07:43 -04:00
EstItemCount : 2 ,
2023-10-24 09:41:11 -07:00
},
2024-09-17 10:07:43 -04:00
},
{
name : "global-with-descendants-wildcard" ,
setupFunc : func ( t * testing . T ) {
globalRole := iam . TestRole ( t , conn , scope . Global . String (), iam . WithGrantScopeIds ([] string { globals . GrantScopeDescendants }))
_ = iam . TestUserRole ( t , conn , globalRole . GetPublicId (), at . GetIamUserId ())
_ = iam . TestRoleGrant ( t , conn , globalRole . GetPublicId (), "ids=*;type=*;actions=*" )
},
res : & pbs . ListTargetsResponse {
Items : totalTars ,
2023-10-24 09:41:11 -07:00
ResponseType : "complete" ,
2023-11-24 17:27:15 -08:00
SortBy : "created_time" ,
SortDir : "desc" ,
2023-10-24 09:41:11 -07:00
EstItemCount : 10 ,
},
2023-11-24 17:27:15 -08:00
},
2024-09-17 10:07:43 -04:00
{
name : "org-with-direct-grants-wildcard" ,
setupFunc : func ( t * testing . T ) {
org1Role := iam . TestRole ( t , conn , org1 . GetPublicId (), iam . WithGrantScopeIds ([] string { proj1 . GetPublicId ()}))
_ = iam . TestUserRole ( t , conn , org1Role . GetPublicId (), at . GetIamUserId ())
_ = iam . TestRoleGrant ( t , conn , org1Role . GetPublicId (), "ids=*;type=*;actions=*" )
org2Role := iam . TestRole ( t , conn , org2 . GetPublicId (), iam . WithGrantScopeIds ([] string { proj2 . GetPublicId ()}))
_ = iam . TestUserRole ( t , conn , org2Role . GetPublicId (), at . GetIamUserId ())
_ = iam . TestRoleGrant ( t , conn , org2Role . GetPublicId (), "ids=*;type=*;actions=*" )
2023-10-24 09:41:11 -07:00
},
2024-09-17 10:07:43 -04:00
res : & pbs . ListTargetsResponse {
Items : totalTars ,
2023-11-24 17:27:15 -08:00
ResponseType : "complete" ,
2024-09-17 10:07:43 -04:00
SortBy : "created_time" ,
2023-11-24 17:27:15 -08:00
SortDir : "desc" ,
EstItemCount : 10 ,
},
2024-09-17 10:07:43 -04:00
},
{
name : "org-with-direct-grants-non-wildcard" ,
setupFunc : func ( t * testing . T ) {
org1Role := iam . TestRole ( t , conn , org1 . GetPublicId (), iam . WithGrantScopeIds ([] string { proj1 . GetPublicId ()}))
_ = iam . TestUserRole ( t , conn , org1Role . GetPublicId (), at . GetIamUserId ())
_ = iam . TestRoleGrant ( t , conn , org1Role . GetPublicId (), "ids=*;type=target;actions=list" )
_ = iam . TestRoleGrant ( t , conn , org1Role . GetPublicId (), fmt . Sprintf ( "ids=%s,%s;actions=*" , totalTars [ 0 ]. Id , totalTars [ 1 ]. Id ))
org2Role := iam . TestRole ( t , conn , org2 . GetPublicId (), iam . WithGrantScopeIds ([] string { proj2 . GetPublicId ()}))
_ = iam . TestUserRole ( t , conn , org2Role . GetPublicId (), at . GetIamUserId ())
_ = iam . TestRoleGrant ( t , conn , org2Role . GetPublicId (), "ids=*;type=target;actions=list" )
_ = iam . TestRoleGrant ( t , conn , org2Role . GetPublicId (), fmt . Sprintf ( "ids=%s,%s;actions=*" , totalTars [ 5 ]. Id , totalTars [ 6 ]. Id ))
},
res : & pbs . ListTargetsResponse {
Items : append ([] * pb . Target {}, append ( append ([] * pb . Target {}, totalTars [ 0 : 2 ] ... ), totalTars [ 5 : 7 ] ... ) ... ),
ResponseType : "complete" ,
2023-11-24 17:27:15 -08:00
SortBy : "created_time" ,
SortDir : "desc" ,
2024-09-17 10:07:43 -04:00
EstItemCount : 4 ,
2023-10-24 09:41:11 -07:00
},
2024-09-17 10:07:43 -04:00
},
{
name : "org-with-children-wildcard" ,
setupFunc : func ( t * testing . T ) {
org1Role := iam . TestRole ( t , conn , org1 . GetPublicId (), iam . WithGrantScopeIds ([] string { globals . GrantScopeChildren }))
_ = iam . TestUserRole ( t , conn , org1Role . GetPublicId (), at . GetIamUserId ())
_ = iam . TestRoleGrant ( t , conn , org1Role . GetPublicId (), "ids=*;type=*;actions=*" )
},
res : & pbs . ListTargetsResponse {
Items : totalTars [ 0 : 5 ],
2023-10-24 09:41:11 -07:00
ResponseType : "complete" ,
2023-11-24 17:27:15 -08:00
SortBy : "created_time" ,
SortDir : "desc" ,
2024-09-17 10:07:43 -04:00
EstItemCount : 5 ,
},
},
}
for _ , tc := range cases {
t . Run ( tc . name , func ( t * testing . T ) {
assert , require := assert . New ( t ), require . New ( t )
_ , err := sqlDB . Exec ( "delete from iam_role" )
require . NoError ( err )
tc . setupFunc ( t )
s , err := testService ( t , context . Background (), conn , kms , wrapper )
require . NoError ( err , "Couldn't create new target service." )
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx := auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
got , gErr := s . ListTargets ( ctx , & pbs . ListTargetsRequest {
ScopeId : scope . Global . String (),
Recursive : true ,
PageSize : tc . pageSize ,
})
if tc . err != nil {
require . Error ( gErr )
assert . True ( errors . Is ( gErr , tc . err ), "got error %v, wanted %v" , gErr , tc . err )
return
}
require . NoError ( gErr )
assert . Equal ( len ( tc . res . Items ), len ( got . Items ))
wantById := make ( map [ string ] * pb . Target , len ( tc . res . Items ))
for _ , t := range tc . res . Items {
wantById [ t . Id ] = t
}
for _ , t := range got . Items {
want , ok := wantById [ t . Id ]
assert . True ( ok , "Got unexpected target with id: %s" , t . Id )
assert . Empty ( cmp . Diff (
t ,
want ,
protocmp . Transform (),
cmpopts . SortSlices ( func ( a , b string ) bool {
return a < b
}),
), "got %v, wanted %v" , t , want )
}
})
}
}
func TestListPagination ( t * testing . T ) {
testListPagination := func ( t * testing . T , useDescendants bool ) {
// Set database read timeout to avoid duplicates in response
oldReadTimeout := globals . RefreshReadLookbackDuration
globals . RefreshReadLookbackDuration = 0
t . Cleanup ( func () {
globals . RefreshReadLookbackDuration = oldReadTimeout
})
ctx := context . Background ()
conn , _ := db . TestSetup ( t , "postgres" )
sqlDB , err := conn . SqlDB ( ctx )
require . NoError ( t , err )
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
rw := db . New ( conn )
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
tokenRepoFn := func () ( * authtoken . Repository , error ) {
return authtoken . NewRepository ( ctx , rw , rw , kms )
}
serversRepoFn := func () ( * server . Repository , error ) {
return server . NewRepository ( ctx , rw , rw , kms )
}
repo , err := target . NewRepository ( ctx , rw , rw , kms )
require . NoError ( t , err )
// We're going to run the same test in two projects; one with
// descendants and one with direct grants in one project and a child
// grant from org in another project
org1 , proj1 := iam . TestScopes ( t , iamRepo )
org2 , proj2 := iam . TestScopes ( t , iamRepo )
at := authtoken . TestAuthToken ( t , conn , kms , scope . Global . String ())
if useDescendants {
r := iam . TestRole ( t , conn , scope . Global . String (), iam . WithGrantScopeIds ([] string { globals . GrantScopeDescendants }))
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
} else {
r1 := iam . TestRole ( t , conn , proj1 . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r1 . GetPublicId (), at . GetIamUserId ())
_ = iam . TestRoleGrant ( t , conn , r1 . GetPublicId (), "ids=*;type=*;actions=*" )
r2 := iam . TestRole ( t , conn , org2 . GetPublicId (), iam . WithGrantScopeIds ([] string { globals . GrantScopeChildren }))
_ = iam . TestUserRole ( t , conn , r2 . GetPublicId (), at . GetIamUserId ())
_ = iam . TestRoleGrant ( t , conn , r2 . GetPublicId (), "ids=*;type=*;actions=*" )
}
hc := static . TestCatalogs ( t , conn , proj1 . GetPublicId (), 1 )[ 0 ]
hss := static . TestSets ( t , conn , hc . GetPublicId (), 2 )
s , err := testService ( t , context . Background (), conn , kms , wrapper )
require . NoError ( t , err )
var allTargets [] * pb . Target
for i := 0 ; i < 10 ; i ++ {
tar := tcp . TestTarget ( ctx , t , conn , proj1 . GetPublicId (), fmt . Sprintf ( "tar-1-%d" , i ), target . WithHostSources ([] string { hss [ 0 ]. GetPublicId (), hss [ 1 ]. GetPublicId ()}))
allTargets = append ( allTargets , & pb . Target {
Id : tar . GetPublicId (),
ScopeId : proj1 . GetPublicId (),
Name : wrapperspb . String ( tar . GetName ()),
Scope : & scopes . ScopeInfo { Id : proj1 . GetPublicId (), Type : scope . Project . String (), ParentScopeId : org1 . GetPublicId ()},
CreatedTime : tar . GetCreateTime (). GetTimestamp (),
UpdatedTime : tar . GetUpdateTime (). GetTimestamp (),
Version : tar . GetVersion (),
Type : tcp . Subtype . String (),
Attrs : & pb . Target_TcpTargetAttributes {},
SessionMaxSeconds : wrapperspb . UInt32 ( 28800 ),
SessionConnectionLimit : wrapperspb . Int32 ( - 1 ),
AuthorizedActions : testAuthorizedActions ,
Address : & wrapperspb . StringValue {},
})
}
for i := 0 ; i < 10 ; i ++ {
tar := tcp . TestTarget ( ctx , t , conn , proj2 . GetPublicId (), fmt . Sprintf ( "tar-2-%d" , i ), target . WithAddress ( fmt . Sprintf ( "127.0.0.%d" , i )))
allTargets = append ( allTargets , & pb . Target {
Id : tar . GetPublicId (),
ScopeId : proj2 . GetPublicId (),
Name : wrapperspb . String ( tar . GetName ()),
Scope : & scopes . ScopeInfo { Id : proj2 . GetPublicId (), Type : scope . Project . String (), ParentScopeId : org2 . GetPublicId ()},
CreatedTime : tar . GetCreateTime (). GetTimestamp (),
UpdatedTime : tar . GetUpdateTime (). GetTimestamp (),
Version : tar . GetVersion (),
Type : tcp . Subtype . String (),
Attrs : & pb . Target_TcpTargetAttributes {},
SessionMaxSeconds : wrapperspb . UInt32 ( 28800 ),
SessionConnectionLimit : wrapperspb . Int32 ( - 1 ),
AuthorizedActions : testAuthorizedActions ,
Address : & wrapperspb . StringValue { Value : fmt . Sprintf ( "127.0.0.%d" , i )},
})
}
// Reverse since we read items in descending order (newest first)
slices . Reverse ( allTargets )
// Run analyze to update postgres estimates
_ , err = sqlDB . ExecContext ( ctx , "analyze" )
require . NoError ( t , err )
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx = auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
// Start paginating, recursively
req := & pbs . ListTargetsRequest {
ScopeId : "global" ,
Recursive : true ,
Filter : "" ,
ListToken : "" ,
PageSize : 2 ,
}
got , err := s . ListTargets ( ctx , req )
require . NoError ( t , err )
require . Len ( t , got . GetItems (), 2 )
// Compare without comparing the list token
assert . Empty ( t ,
cmp . Diff (
got ,
& pbs . ListTargetsResponse {
Items : allTargets [ 0 : 2 ],
ResponseType : "delta" ,
SortBy : "created_time" ,
SortDir : "desc" ,
RemovedIds : nil ,
EstItemCount : 20 ,
},
cmpopts . SortSlices ( func ( a , b string ) bool {
return a < b
}),
protocmp . Transform (),
protocmp . IgnoreFields ( & pbs . ListTargetsResponse {}, "list_token" ),
),
)
// Request second page
req . ListToken = got . ListToken
got , err = s . ListTargets ( ctx , req )
require . NoError ( t , err )
require . Len ( t , got . GetItems (), 2 )
// Compare without comparing the list token
assert . Empty ( t ,
cmp . Diff (
got ,
& pbs . ListTargetsResponse {
Items : allTargets [ 2 : 4 ],
ResponseType : "delta" ,
SortBy : "created_time" ,
SortDir : "desc" ,
RemovedIds : nil ,
EstItemCount : 20 ,
},
cmpopts . SortSlices ( func ( a , b string ) bool {
return a < b
}),
protocmp . Transform (),
protocmp . IgnoreFields ( & pbs . ListTargetsResponse {}, "list_token" ),
),
)
// Request rest of results
req . ListToken = got . ListToken
req . PageSize = 20
got , err = s . ListTargets ( ctx , req )
require . NoError ( t , err )
require . Len ( t , got . GetItems (), 16 )
// Compare without comparing the list token
assert . Empty ( t ,
cmp . Diff (
got ,
& pbs . ListTargetsResponse {
Items : allTargets [ 4 :],
ResponseType : "complete" ,
SortBy : "created_time" ,
SortDir : "desc" ,
RemovedIds : nil ,
EstItemCount : 20 ,
},
cmpopts . SortSlices ( func ( a , b string ) bool {
return a < b
}),
protocmp . Transform (),
protocmp . IgnoreFields ( & pbs . ListTargetsResponse {}, "list_token" ),
),
)
// Create another target
tar := tcp . TestTarget ( ctx , t , conn , proj1 . GetPublicId (), "test-target-1" , target . WithHostSources ([] string { hss [ 0 ]. GetPublicId (), hss [ 1 ]. GetPublicId ()}))
newTarget := & pb . Target {
Id : tar . GetPublicId (),
ScopeId : proj1 . GetPublicId (),
Name : wrapperspb . String ( tar . GetName ()),
Scope : & scopes . ScopeInfo { Id : proj1 . GetPublicId (), Type : scope . Project . String (), ParentScopeId : org1 . GetPublicId ()},
CreatedTime : tar . GetCreateTime (). GetTimestamp (),
UpdatedTime : tar . GetUpdateTime (). GetTimestamp (),
Version : tar . GetVersion (),
Type : tcp . Subtype . String (),
Attrs : & pb . Target_TcpTargetAttributes {},
SessionMaxSeconds : wrapperspb . UInt32 ( 28800 ),
SessionConnectionLimit : wrapperspb . Int32 ( - 1 ),
AuthorizedActions : testAuthorizedActions ,
Address : & wrapperspb . StringValue {},
}
// Add to the front since it's most recently updated
allTargets = append ([] * pb . Target { newTarget }, allTargets ... )
tar = tcp . TestTarget ( ctx , t , conn , proj2 . GetPublicId (), "test-target-2" , target . WithAddress ( fmt . Sprintf ( "127.0.0.11" )))
newTarget = & pb . Target {
Id : tar . GetPublicId (),
ScopeId : proj2 . GetPublicId (),
Name : wrapperspb . String ( tar . GetName ()),
Scope : & scopes . ScopeInfo { Id : proj2 . GetPublicId (), Type : scope . Project . String (), ParentScopeId : org2 . GetPublicId ()},
CreatedTime : tar . GetCreateTime (). GetTimestamp (),
UpdatedTime : tar . GetUpdateTime (). GetTimestamp (),
Version : tar . GetVersion (),
Type : tcp . Subtype . String (),
Attrs : & pb . Target_TcpTargetAttributes {},
SessionMaxSeconds : wrapperspb . UInt32 ( 28800 ),
SessionConnectionLimit : wrapperspb . Int32 ( - 1 ),
AuthorizedActions : testAuthorizedActions ,
Address : & wrapperspb . StringValue { Value : fmt . Sprintf ( "127.0.0.11" )},
}
allTargets = append ([] * pb . Target { newTarget }, allTargets ... )
// Leaving this function here as it is very useful if test objects change
/*
printNames := func(step string, tars []*pb.Target) {
names := make([]string, len(tars))
for i, t := range tars {
names[i] = t.GetName().GetValue()
}
log.Println(step, pretty.Sprint(strings.Join(names, ", ")))
}
*/
// printNames("before delete ", allTargets)
// Delete one of the other targets in each project
_ , err = repo . DeleteTarget ( ctx , allTargets [ len ( allTargets ) - 11 ]. Id )
require . NoError ( t , err )
deletedTarget1 := allTargets [ len ( allTargets ) - 11 ]
allTargets = append ( allTargets [: len ( allTargets ) - 11 ], allTargets [ len ( allTargets ) - 11 + 1 :] ... )
// printNames("after first delete ", allTargets)
_ , err = repo . DeleteTarget ( ctx , allTargets [ len ( allTargets ) - 1 ]. Id )
require . NoError ( t , err )
deletedTarget2 := allTargets [ len ( allTargets ) - 1 ]
allTargets = allTargets [: len ( allTargets ) - 1 ]
// printNames("after second delete", allTargets)
// Update two of the other targets
allTargets [ 2 ]. Name = wrapperspb . String ( "new-name-1" )
allTargets [ 2 ]. Version = 2
updatedTarget := & tcp . Target {
Target : & store . Target {
PublicId : allTargets [ 2 ]. Id ,
Name : allTargets [ 2 ]. Name . GetValue (),
ProjectId : allTargets [ 2 ]. ScopeId ,
2023-10-24 09:41:11 -07:00
},
2024-09-17 10:07:43 -04:00
}
tg , _ , err := repo . UpdateTarget ( ctx , updatedTarget , 1 , [] string { "name" })
require . NoError ( t , err )
allTargets [ 2 ]. UpdatedTime = tg . GetUpdateTime (). GetTimestamp ()
allTargets [ 2 ]. Version = tg . GetVersion ()
// Add to the front since it's most recently updated
newAllTargets := append ([] * pb . Target { allTargets [ 2 ]}, allTargets [ 0 : 2 ] ... )
newAllTargets = append ( newAllTargets , allTargets [ 3 :] ... )
allTargets = newAllTargets
// printNames("after first update ", allTargets)
allTargets [ 11 ]. Name = wrapperspb . String ( "new-name-11" )
allTargets [ 11 ]. Version = 2
updatedTarget = & tcp . Target {
Target : & store . Target {
PublicId : allTargets [ 11 ]. Id ,
Name : allTargets [ 11 ]. Name . GetValue (),
ProjectId : allTargets [ 11 ]. ScopeId ,
},
}
tg , _ , err = repo . UpdateTarget ( ctx , updatedTarget , 1 , [] string { "name" })
require . NoError ( t , err )
allTargets [ 11 ]. UpdatedTime = tg . GetUpdateTime (). GetTimestamp ()
allTargets [ 11 ]. Version = tg . GetVersion ()
// Add to the front since it's most recently updated
newAllTargets = append ([] * pb . Target { allTargets [ 11 ]}, allTargets [ 0 : 11 ] ... )
newAllTargets = append ( newAllTargets , allTargets [ 12 :] ... )
allTargets = newAllTargets
// printNames("after second update", allTargets)
// Run analyze to update postgres estimates
_ , err = sqlDB . ExecContext ( ctx , "analyze" )
require . NoError ( t , err )
// Request updated results
req . ListToken = got . ListToken
req . PageSize = 2
got , err = s . ListTargets ( ctx , req )
require . NoError ( t , err )
require . Len ( t , got . GetItems (), 2 )
// Compare without comparing the list token
assert . Empty ( t ,
cmp . Diff (
got ,
& pbs . ListTargetsResponse {
Items : [] * pb . Target { allTargets [ 0 ], allTargets [ 1 ]},
ResponseType : "delta" ,
SortBy : "updated_time" ,
SortDir : "desc" ,
// Should contain the deleted target
RemovedIds : [] string { deletedTarget1 . Id , deletedTarget2 . Id },
EstItemCount : 20 ,
},
cmpopts . SortSlices ( func ( a , b string ) bool {
return a < b
}),
protocmp . Transform (),
protocmp . IgnoreFields ( & pbs . ListTargetsResponse {}, "list_token" ),
),
)
// Get next page
req . ListToken = got . ListToken
got , err = s . ListTargets ( ctx , req )
require . NoError ( t , err )
require . Len ( t , got . GetItems (), 2 )
// Compare without comparing the list token
assert . Empty ( t ,
cmp . Diff (
got ,
& pbs . ListTargetsResponse {
Items : [] * pb . Target { allTargets [ 2 ], allTargets [ 3 ]},
ResponseType : "complete" ,
SortBy : "updated_time" ,
SortDir : "desc" ,
RemovedIds : nil ,
EstItemCount : 20 ,
},
cmpopts . SortSlices ( func ( a , b string ) bool {
return a < b
}),
protocmp . Transform (),
protocmp . IgnoreFields ( & pbs . ListTargetsResponse {}, "list_token" ),
),
)
// Request new page with filter requiring looping
// to fill the page.
req . ListToken = ""
req . PageSize = 1
req . Filter = fmt . Sprintf ( `"/item/id"==%q or "/item/id"==%q` , allTargets [ len ( allTargets ) - 2 ]. Id , allTargets [ len ( allTargets ) - 1 ]. Id )
got , err = s . ListTargets ( ctx , req )
require . NoError ( t , err )
require . Len ( t , got . GetItems (), 1 )
assert . Empty ( t ,
cmp . Diff (
got ,
& pbs . ListTargetsResponse {
Items : [] * pb . Target { allTargets [ len ( allTargets ) - 2 ]},
ResponseType : "delta" ,
SortBy : "created_time" ,
SortDir : "desc" ,
// Should be empty again
RemovedIds : nil ,
EstItemCount : 20 ,
},
cmpopts . SortSlices ( func ( a , b string ) bool {
return a < b
}),
protocmp . Transform (),
protocmp . IgnoreFields ( & pbs . ListTargetsResponse {}, "list_token" ),
),
)
req . ListToken = got . ListToken
// Get the second page
got , err = s . ListTargets ( ctx , req )
require . NoError ( t , err )
require . Len ( t , got . GetItems (), 1 )
assert . Empty ( t ,
cmp . Diff (
got ,
& pbs . ListTargetsResponse {
Items : [] * pb . Target { allTargets [ len ( allTargets ) - 1 ]},
ResponseType : "complete" ,
SortBy : "created_time" ,
SortDir : "desc" ,
RemovedIds : nil ,
EstItemCount : 20 ,
},
cmpopts . SortSlices ( func ( a , b string ) bool {
return a < b
}),
protocmp . Transform (),
protocmp . IgnoreFields ( & pbs . ListTargetsResponse {}, "list_token" ),
),
)
// Create unauthenticated user
unauthAt := authtoken . TestAuthToken ( t , conn , kms , org1 . GetPublicId ())
unauthR := iam . TestRole ( t , conn , proj1 . GetPublicId ())
_ = iam . TestUserRole ( t , conn , unauthR . GetPublicId (), unauthAt . GetIamUserId ())
// Make a request with the unauthenticated user,
// ensure the response contains the pagination parameters.
requestInfo = authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : unauthAt . GetPublicId (),
Token : unauthAt . GetToken (),
}
requestContext = context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx = auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
got , err = s . ListTargets ( ctx , & pbs . ListTargetsRequest {
ScopeId : "global" ,
Recursive : true ,
})
require . NoError ( t , err )
assert . Empty ( t , got . Items )
assert . Equal ( t , "created_time" , got . SortBy )
assert . Equal ( t , "desc" , got . SortDir )
assert . Equal ( t , "complete" , got . ResponseType )
}
t . Run ( "with-descendants" , func ( t * testing . T ) {
testListPagination ( t , true )
})
t . Run ( "without-descendants" , func ( t * testing . T ) {
testListPagination ( t , false )
2024-02-15 09:26:29 -08:00
})
2023-10-24 09:41:11 -07:00
}
2020-09-01 15:05:46 -07:00
func TestDelete ( t * testing . T ) {
t . Parallel ()
2023-06-06 17:09:08 -04:00
ctx := context . Background ()
2020-09-01 15:05:46 -07:00
conn , _ := db . TestSetup ( t , "postgres" )
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
2022-07-29 17:24:39 +00:00
rw := db . New ( conn )
2021-03-25 03:15:43 -04:00
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
2022-07-29 17:24:39 +00:00
tokenRepoFn := func () ( * authtoken . Repository , error ) {
2023-06-06 17:09:08 -04:00
return authtoken . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
2021-03-25 03:15:43 -04:00
2022-07-29 17:24:39 +00:00
org , proj := iam . TestScopes ( t , iamRepo )
at := authtoken . TestAuthToken ( t , conn , kms , org . GetPublicId ())
r := iam . TestRole ( t , conn , proj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2022-07-29 17:24:39 +00:00
2021-11-04 11:44:22 -04:00
tar := tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "test" )
2020-09-01 15:05:46 -07:00
2023-06-06 17:09:08 -04:00
s , err := testService ( t , ctx , conn , kms , wrapper )
2020-09-01 15:05:46 -07:00
require . NoError ( t , err , "Couldn't create a new target service." )
cases := [] struct {
name string
scopeId string
req * pbs . DeleteTargetRequest
res * pbs . DeleteTargetResponse
2020-09-23 08:10:27 -07:00
err error
2020-09-01 15:05:46 -07:00
}{
{
name : "Delete an Existing Target" ,
scopeId : proj . GetPublicId (),
req : & pbs . DeleteTargetRequest {
Id : tar . GetPublicId (),
},
},
{
name : "Delete Not Existing Target" ,
scopeId : proj . GetPublicId (),
req : & pbs . DeleteTargetRequest {
2023-03-10 15:06:39 -05:00
Id : globals . TcpTargetPrefix + "_doesntexis" ,
2020-09-01 15:05:46 -07:00
},
2020-09-23 08:10:27 -07:00
err : handlers . ApiErrorWithCode ( codes . NotFound ),
2020-09-01 15:05:46 -07:00
},
{
name : "Bad target id formatting" ,
scopeId : proj . GetPublicId (),
req : & pbs . DeleteTargetRequest {
2023-03-10 15:06:39 -05:00
Id : globals . TcpTargetPrefix + "_bad_format" ,
2020-09-01 15:05:46 -07:00
},
2020-09-23 08:10:27 -07:00
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
}
for _ , tc := range cases {
t . Run ( tc . name , func ( t * testing . T ) {
2020-09-23 08:10:27 -07:00
assert , require := assert . New ( t ), require . New ( t )
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
2023-06-06 17:09:08 -04:00
requestContext := context . WithValue ( ctx , requests . ContextRequestInformationKey , & requests . RequestContext {})
2022-07-29 17:24:39 +00:00
ctx := auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
got , gErr := s . DeleteTarget ( ctx , tc . req )
2020-09-23 08:10:27 -07:00
if tc . err != nil {
require . Error ( gErr )
assert . True ( errors . Is ( gErr , tc . err ), "DeleteTarget(%+v) got error %v, wanted %v" , tc . req , gErr , tc . err )
}
2023-10-31 13:44:17 +00:00
assert . Empty ( cmp . Diff (
tc . res ,
got ,
protocmp . Transform (),
cmpopts . SortSlices ( func ( a , b string ) bool {
return a < b
}),
), "DeleteTarget(%q) got response %q, wanted %q" , tc . req , got , tc . res )
2020-09-01 15:05:46 -07:00
})
}
}
func TestDelete_twice ( t * testing . T ) {
t . Parallel ()
2020-09-23 08:10:27 -07:00
assert , require := assert . New ( t ), require . New ( t )
2020-09-01 15:05:46 -07:00
conn , _ := db . TestSetup ( t , "postgres" )
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
2022-07-29 17:24:39 +00:00
rw := db . New ( conn )
2021-11-04 11:44:22 -04:00
ctx := context . Background ()
2021-03-25 03:15:43 -04:00
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
2022-07-29 17:24:39 +00:00
tokenRepoFn := func () ( * authtoken . Repository , error ) {
2023-06-06 17:09:08 -04:00
return authtoken . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
2021-03-25 03:15:43 -04:00
2022-07-29 17:24:39 +00:00
org , proj := iam . TestScopes ( t , iamRepo )
at := authtoken . TestAuthToken ( t , conn , kms , org . GetPublicId ())
r := iam . TestRole ( t , conn , proj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2020-09-01 15:05:46 -07:00
2021-11-04 11:44:22 -04:00
tar := tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "test" )
2020-09-01 15:05:46 -07:00
2022-06-15 08:56:24 -07:00
s , err := testService ( t , context . Background (), conn , kms , wrapper )
2020-09-23 08:10:27 -07:00
require . NoError ( err , "Couldn't create a new target service." )
2020-09-01 15:05:46 -07:00
req := & pbs . DeleteTargetRequest {
Id : tar . GetPublicId (),
}
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx = auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
2020-09-08 23:57:26 -04:00
_ , gErr := s . DeleteTarget ( ctx , req )
2020-09-01 15:05:46 -07:00
assert . NoError ( gErr , "First attempt" )
_ , gErr = s . DeleteTarget ( ctx , req )
assert . Error ( gErr , "Second attempt" )
2020-09-23 08:10:27 -07:00
assert . True ( errors . Is ( gErr , handlers . ApiErrorWithCode ( codes . NotFound )), "Expected permission denied for the second delete." )
2020-09-01 15:05:46 -07:00
}
func TestCreate ( t * testing . T ) {
2023-06-06 17:09:08 -04:00
ctx := context . Background ()
2020-09-01 15:05:46 -07:00
conn , _ := db . TestSetup ( t , "postgres" )
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
2022-07-29 17:24:39 +00:00
rw := db . New ( conn )
2021-03-25 03:15:43 -04:00
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
2022-07-29 17:24:39 +00:00
tokenRepoFn := func () ( * authtoken . Repository , error ) {
2023-06-06 17:09:08 -04:00
return authtoken . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
2021-03-25 03:15:43 -04:00
org , proj := iam . TestScopes ( t , iamRepo )
2022-07-29 17:24:39 +00:00
at := authtoken . TestAuthToken ( t , conn , kms , org . GetPublicId ())
2024-03-12 13:57:47 -07:00
r := iam . TestRole ( t , conn , "global" )
2022-07-29 17:24:39 +00:00
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2024-03-12 13:57:47 -07:00
_ = iam . TestRoleGrantScope ( t , conn , r . GetPublicId (), globals . GrantScopeDescendants )
2020-09-01 15:05:46 -07:00
2025-01-08 15:18:03 +00:00
// Ensure we are using the OSS worker filter function. This prevents us from
// running tests in parallel.
server . TestUseCommunityFilterWorkersFn ( t )
2022-11-30 15:23:37 -05:00
2020-09-01 15:05:46 -07:00
cases := [] struct {
2023-02-16 11:36:23 -08:00
name string
req * pbs . CreateTargetRequest
res * pbs . CreateTargetResponse
err error
errStr string
2020-09-01 15:05:46 -07:00
}{
{
name : "Create a valid target" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
ScopeId : proj . GetPublicId (),
Name : wrapperspb . String ( "name" ),
Description : wrapperspb . String ( "desc" ),
2023-11-02 16:03:47 -04:00
Type : tcp . Subtype . String (),
2022-04-13 16:27:48 -04:00
Attrs : & pb . Target_TcpTargetAttributes {
TcpTargetAttributes : & pb . TcpTargetAttributes {
2023-04-21 06:50:53 -04:00
DefaultPort : wrapperspb . UInt32 ( 2 ),
DefaultClientPort : wrapperspb . UInt32 ( 3 ),
2022-04-13 16:27:48 -04:00
},
},
2022-11-30 15:23:37 -05:00
EgressWorkerFilter : wrapperspb . String ( `type == "bar"` ),
2020-09-01 15:05:46 -07:00
}},
res : & pbs . CreateTargetResponse {
2023-03-10 15:06:39 -05:00
Uri : fmt . Sprintf ( "targets/%s_" , globals . TcpTargetPrefix ),
2020-09-01 15:05:46 -07:00
Item : & pb . Target {
ScopeId : proj . GetPublicId (),
2021-03-25 03:15:43 -04:00
Scope : & scopes . ScopeInfo { Id : proj . GetPublicId (), Type : scope . Project . String (), ParentScopeId : org . GetPublicId ()},
2020-09-01 15:05:46 -07:00
Name : wrapperspb . String ( "name" ),
Description : wrapperspb . String ( "desc" ),
2023-11-02 16:03:47 -04:00
Type : tcp . Subtype . String (),
2022-04-13 16:27:48 -04:00
Attrs : & pb . Target_TcpTargetAttributes {
TcpTargetAttributes : & pb . TcpTargetAttributes {
2023-04-21 06:50:53 -04:00
DefaultPort : wrapperspb . UInt32 ( 2 ),
DefaultClientPort : wrapperspb . UInt32 ( 3 ),
2022-04-13 16:27:48 -04:00
},
},
2020-09-20 15:53:49 -04:00
SessionMaxSeconds : wrapperspb . UInt32 ( 28800 ),
2022-07-06 09:02:56 -07:00
SessionConnectionLimit : wrapperspb . Int32 ( - 1 ),
2021-04-23 09:13:37 -05:00
AuthorizedActions : testAuthorizedActions ,
2022-11-30 15:23:37 -05:00
EgressWorkerFilter : wrapperspb . String ( `type == "bar"` ),
2022-12-06 12:33:28 -08:00
Address : & wrapperspb . StringValue {},
2020-09-01 15:05:46 -07:00
},
},
},
2024-03-12 13:57:47 -07:00
{
name : "Create a valid target with two aliases" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
ScopeId : proj . GetPublicId (),
Name : wrapperspb . String ( "target_with_aliases" ),
Type : tcp . Subtype . String (),
Attrs : & pb . Target_TcpTargetAttributes {
TcpTargetAttributes : & pb . TcpTargetAttributes {
DefaultPort : wrapperspb . UInt32 ( 2 ),
},
},
WithAliases : [] * pb . Alias {
{
Value : "create-two-aliasses1" ,
ScopeId : "global" ,
},
{
Value : "create-two-aliasses2" ,
ScopeId : "global" ,
},
},
}},
res : & pbs . CreateTargetResponse {
Uri : fmt . Sprintf ( "targets/%s_" , globals . TcpTargetPrefix ),
Item : & pb . Target {
ScopeId : proj . GetPublicId (),
Scope : & scopes . ScopeInfo { Id : proj . GetPublicId (), Type : scope . Project . String (), ParentScopeId : org . GetPublicId ()},
Name : wrapperspb . String ( "target_with_aliases" ),
Type : tcp . Subtype . String (),
Attrs : & pb . Target_TcpTargetAttributes {
TcpTargetAttributes : & pb . TcpTargetAttributes {
DefaultPort : wrapperspb . UInt32 ( 2 ),
},
},
Aliases : [] * pb . Alias {
{
Value : "create-two-aliasses1" ,
},
{
Value : "create-two-aliasses2" ,
},
},
SessionMaxSeconds : wrapperspb . UInt32 ( 28800 ),
SessionConnectionLimit : wrapperspb . Int32 ( - 1 ),
AuthorizedActions : testAuthorizedActions ,
Address : & wrapperspb . StringValue {},
},
},
},
{
name : "Create a target with alias specifying the id" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
ScopeId : proj . GetPublicId (),
Name : wrapperspb . String ( "target_with_invalid_alias" ),
Type : tcp . Subtype . String (),
Attrs : & pb . Target_TcpTargetAttributes {
TcpTargetAttributes : & pb . TcpTargetAttributes {
DefaultPort : wrapperspb . UInt32 ( 2 ),
},
},
WithAliases : [] * pb . Alias {
{
Id : "alt_1234567890" ,
Value : "id-specified" ,
ScopeId : "global" ,
},
},
}},
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
name : "Create a target with invalid alias" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
ScopeId : proj . GetPublicId (),
Name : wrapperspb . String ( "target_with_invalid_alias" ),
Type : tcp . Subtype . String (),
Attrs : & pb . Target_TcpTargetAttributes {
TcpTargetAttributes : & pb . TcpTargetAttributes {
DefaultPort : wrapperspb . UInt32 ( 2 ),
},
},
WithAliases : [] * pb . Alias {
{
Value : "invalid alias" ,
ScopeId : "global" ,
},
},
}},
errStr : "unable to create target alias" ,
},
{
name : "Create a target with invalid scope" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
ScopeId : proj . GetPublicId (),
Name : wrapperspb . String ( "target_with_invalid_alias" ),
Type : tcp . Subtype . String (),
Attrs : & pb . Target_TcpTargetAttributes {
TcpTargetAttributes : & pb . TcpTargetAttributes {
DefaultPort : wrapperspb . UInt32 ( 2 ),
},
},
WithAliases : [] * pb . Alias {
{
Value : "alias.invalid.scope" ,
ScopeId : proj . GetPublicId (),
},
},
}},
errStr : "unable to create target alias" ,
},
{
name : "Create a target with duplicate aliasses" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
ScopeId : proj . GetPublicId (),
Name : wrapperspb . String ( "target_with_invalid_alias" ),
Type : tcp . Subtype . String (),
Attrs : & pb . Target_TcpTargetAttributes {
TcpTargetAttributes : & pb . TcpTargetAttributes {
DefaultPort : wrapperspb . UInt32 ( 2 ),
},
},
WithAliases : [] * pb . Alias {
{
Value : "duplicate-alias" ,
ScopeId : "global" ,
},
{
Value : "duplicate-alias" ,
ScopeId : "global" ,
},
},
}},
errStr : "duplicate key value violates unique constraint" ,
},
2022-06-13 08:26:24 -07:00
{
name : "Create a target with no port" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
2022-11-30 15:23:37 -05:00
ScopeId : proj . GetPublicId (),
Name : wrapperspb . String ( "name" ),
Description : wrapperspb . String ( "desc" ),
2023-11-02 16:03:47 -04:00
Type : tcp . Subtype . String (),
2022-11-30 15:23:37 -05:00
EgressWorkerFilter : wrapperspb . String ( `type == "bar"` ),
2022-06-13 08:26:24 -07:00
}},
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
2020-09-01 15:05:46 -07:00
{
name : "Create with default port 0" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
Name : wrapperspb . String ( "name" ),
Description : wrapperspb . String ( "desc" ),
2023-11-02 16:03:47 -04:00
Type : tcp . Subtype . String (),
2022-04-13 16:27:48 -04:00
Attrs : & pb . Target_TcpTargetAttributes {
TcpTargetAttributes : & pb . TcpTargetAttributes {
2023-04-21 06:50:53 -04:00
DefaultPort : wrapperspb . UInt32 ( 2 ),
DefaultClientPort : wrapperspb . UInt32 ( 3 ),
2022-04-13 16:27:48 -04:00
},
},
2020-09-01 15:05:46 -07:00
}},
2020-09-23 08:10:27 -07:00
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
{
name : "Create with unknown type" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
Name : wrapperspb . String ( "name" ),
Description : wrapperspb . String ( "desc" ),
Type : "ThisIsMadeUp" ,
}},
2020-09-23 08:10:27 -07:00
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
{
name : "Create with no type" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
Name : wrapperspb . String ( "name" ),
Description : wrapperspb . String ( "desc" ),
}},
2020-09-23 08:10:27 -07:00
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
{
name : "Can't specify Id" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
Id : "not allowed to be set" ,
}},
2020-09-23 08:10:27 -07:00
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
{
name : "Can't specify Created Time" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
2021-04-23 09:13:37 -05:00
CreatedTime : timestamppb . Now (),
2020-09-01 15:05:46 -07:00
}},
2020-09-23 08:10:27 -07:00
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
{
name : "Can't specify Update Time" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
2021-04-23 09:13:37 -05:00
UpdatedTime : timestamppb . Now (),
2020-09-01 15:05:46 -07:00
}},
2020-09-23 08:10:27 -07:00
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
2021-02-02 11:03:47 -08:00
{
name : "Invalid worker filter expression" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
2022-11-30 15:23:37 -05:00
EgressWorkerFilter : wrapperspb . String ( "bad expression" ),
}},
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
name : "Deprecated worker filter" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
WorkerFilter : wrapperspb . String ( `"/name" matches "test-worker"` ),
}},
2023-02-16 11:36:23 -08:00
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2023-02-16 17:34:25 -08:00
errStr : expectedDeprecatedWorkerFilterError ,
2022-11-30 15:23:37 -05:00
},
{
name : "Ingress filter unsupported on OSS" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
IngressWorkerFilter : wrapperspb . String ( `"/name" matches "test-worker"` ),
2021-02-02 11:03:47 -08:00
}},
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
2022-12-06 12:33:28 -08:00
{
name : "Invalid address length" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
Address : wrapperspb . String ( "ab" ),
}},
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
name : "Invalid address w/ port" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
Address : wrapperspb . String ( "8.8.8.8:80" ),
}},
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
name : "Invalid address not parsable" ,
req : & pbs . CreateTargetRequest { Item : & pb . Target {
Address : wrapperspb . String ( "aaa.8bc.8.8:80:abc" ),
}},
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
2020-09-01 15:05:46 -07:00
}
for _ , tc := range cases {
t . Run ( tc . name , func ( t * testing . T ) {
assert , require := assert . New ( t ), require . New ( t )
2022-06-15 08:56:24 -07:00
s , err := testService ( t , context . Background (), conn , kms , wrapper )
2020-09-01 15:05:46 -07:00
require . NoError ( err , "Failed to create a new host set service." )
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx := auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
got , gErr := s . CreateTarget ( ctx , tc . req )
2024-03-12 13:57:47 -07:00
if tc . err != nil || tc . errStr != "" {
2020-09-23 08:10:27 -07:00
require . Error ( gErr )
2024-03-12 13:57:47 -07:00
if tc . err != nil {
assert . True ( errors . Is ( gErr , tc . err ), "CreateTarget(%+v) got error %v, wanted %v" , tc . req , gErr , tc . err )
}
2023-02-16 11:36:23 -08:00
if tc . errStr != "" {
2024-03-12 13:57:47 -07:00
assert . ErrorContains ( gErr , tc . errStr )
2023-02-16 11:36:23 -08:00
}
2021-02-02 11:03:47 -08:00
} else {
assert . Nil ( gErr , "Unexpected err: %v" , gErr )
2020-09-23 08:10:27 -07:00
}
2021-02-02 11:03:47 -08:00
2020-09-01 15:05:46 -07:00
if got != nil {
assert . Contains ( got . GetUri (), tc . res . GetUri ())
2023-03-10 15:06:39 -05:00
assert . True ( strings . HasPrefix ( got . GetItem (). GetId (), globals . TcpTargetPrefix ), got . GetItem (). GetId ())
2020-09-01 15:05:46 -07:00
// 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
}
if tc . res != nil {
tc . res . Item . Version = 1
}
2023-10-31 13:44:17 +00:00
assert . Empty ( cmp . Diff (
got ,
tc . res ,
protocmp . Transform (),
2024-03-12 13:57:47 -07:00
// These are generated, so we don't know what they are when
// specifying the expected case.
protocmp . IgnoreFields ( & pb . Alias {}, "id" ),
2023-10-31 13:44:17 +00:00
cmpopts . SortSlices ( func ( a , b string ) bool {
return a < b
}),
), "CreateTarget(%q)\n got response %q\n, wanted %q\n" , tc . req , got , tc . res )
2020-09-01 15:05:46 -07:00
})
}
}
2024-03-12 13:57:47 -07:00
func TestCreate_AliasAuthCheck ( t * testing . T ) {
ctx := context . Background ()
conn , _ := db . TestSetup ( t , "postgres" )
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
rw := db . New ( conn )
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
tokenRepoFn := func () ( * authtoken . Repository , error ) {
return authtoken . NewRepository ( ctx , rw , rw , kms )
}
serversRepoFn := func () ( * server . Repository , error ) {
return server . NewRepository ( ctx , rw , rw , kms )
}
org , proj := iam . TestScopes ( t , iamRepo )
at := authtoken . TestAuthToken ( t , conn , kms , org . GetPublicId ())
// Both users can create targets
allProjectR := iam . TestRole ( t , conn , proj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , allProjectR . GetPublicId (), at . GetIamUserId ())
_ = iam . TestRoleGrant ( t , conn , allProjectR . GetPublicId (), "ids=*;type=*;actions=*" )
req := & pb . Target {
ScopeId : proj . GetPublicId (),
Name : wrapperspb . String ( "name" ),
Type : tcp . Subtype . String (),
Attrs : & pb . Target_TcpTargetAttributes {
TcpTargetAttributes : & pb . TcpTargetAttributes {
DefaultPort : wrapperspb . UInt32 ( 2 ),
},
},
WithAliases : [] * pb . Alias {
{
Value : "alias-allowed" ,
ScopeId : "global" ,
},
},
}
2025-01-08 15:18:03 +00:00
// Ensure we are using the OSS worker filter function. This prevents us from
// running tests in parallel.
server . TestUseCommunityFilterWorkersFn ( t )
2024-03-12 13:57:47 -07:00
s , err := testService ( t , context . Background (), conn , kms , wrapper )
require . NoError ( t , err , "Failed to create a new host set service." )
t . Run ( "disallowed user creating target" , func ( t * testing . T ) {
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx := auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
resp , err := s . CreateTarget ( ctx , & pbs . CreateTargetRequest { Item : req })
require . Error ( t , err )
require . Nil ( t , resp )
assert . ErrorContains ( t , err , "PermissionDenied" )
})
t . Run ( "allowed user creating a target" , func ( t * testing . T ) {
// only aliasAllowedAt can create aliases
aliasR := iam . TestRole ( t , conn , "global" )
_ = iam . TestUserRole ( t , conn , aliasR . GetPublicId (), at . GetIamUserId ())
_ = iam . TestRoleGrant ( t , conn , aliasR . GetPublicId (), "ids=*;type=alias;actions=*" )
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx := auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
resp , err := s . CreateTarget ( ctx , & pbs . CreateTargetRequest { Item : req })
require . NoError ( t , err )
require . NotNil ( t , resp )
})
}
2020-09-01 15:05:46 -07:00
func TestUpdate ( t * testing . T ) {
2023-06-06 17:09:08 -04:00
ctx := context . Background ()
2020-09-01 15:05:46 -07:00
conn , _ := db . TestSetup ( t , "postgres" )
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
2022-07-29 17:24:39 +00:00
rw := db . New ( conn )
2021-03-25 03:15:43 -04:00
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
2022-07-29 17:24:39 +00:00
tokenRepoFn := func () ( * authtoken . Repository , error ) {
2023-06-06 17:09:08 -04:00
return authtoken . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
2021-03-25 03:15:43 -04:00
org , proj := iam . TestScopes ( t , iamRepo )
2022-07-29 17:24:39 +00:00
at := authtoken . TestAuthToken ( t , conn , kms , org . GetPublicId ())
r := iam . TestRole ( t , conn , proj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2020-09-01 15:05:46 -07:00
2022-08-23 17:27:56 +01:00
repoFn := func ( o ... target . Option ) ( * target . Repository , error ) {
2022-08-23 18:44:10 +01:00
return target . NewRepository ( ctx , rw , rw , kms )
2020-09-01 15:05:46 -07:00
}
repo , err := repoFn ()
require . NoError ( t , err , "Couldn't create new target repo." )
hc := static . TestCatalogs ( t , conn , proj . GetPublicId (), 1 )[ 0 ]
hs := static . TestSets ( t , conn , hc . GetPublicId (), 2 )
2021-07-30 08:48:03 -04:00
hostSourceIds := [] string { hs [ 0 ]. GetPublicId (), hs [ 1 ]. GetPublicId ()}
hostSources := [] * pb . HostSource {
{ Id : hs [ 0 ]. GetPublicId (), HostCatalogId : hs [ 0 ]. GetCatalogId ()},
{ Id : hs [ 1 ]. GetPublicId (), HostCatalogId : hs [ 1 ]. GetCatalogId ()},
}
2020-09-01 15:05:46 -07:00
2023-11-02 16:03:47 -04:00
ttar , err := target . New ( ctx , tcp . Subtype , proj . GetPublicId (),
2022-06-13 08:26:24 -07:00
target . WithName ( "default" ),
target . WithDescription ( "default" ),
target . WithSessionMaxSeconds ( 1 ),
target . WithSessionConnectionLimit ( 1 ),
2023-04-21 06:50:53 -04:00
target . WithDefaultPort ( 2 ),
target . WithDefaultClientPort ( 3 ))
2021-11-04 11:44:22 -04:00
require . NoError ( t , err )
2023-03-30 15:19:30 -04:00
tar , err := repo . CreateTarget ( context . Background (), ttar )
2021-10-22 08:51:46 -04:00
require . NoError ( t , err )
2023-03-30 15:19:30 -04:00
tar , err = repo . AddTargetHostSources ( context . Background (), tar . GetPublicId (), tar . GetVersion (), [] string { hs [ 0 ]. GetPublicId (), hs [ 1 ]. GetPublicId ()})
2020-09-01 15:05:46 -07:00
require . NoError ( t , err )
resetTarget := func () {
2023-03-30 15:19:30 -04:00
itar , err := repo . LookupTarget ( context . Background (), tar . GetPublicId ())
2022-06-13 08:26:24 -07:00
require . NoError ( t , err )
2023-03-30 15:19:30 -04:00
tar , _ , err = repo . UpdateTarget ( context . Background (), tar , itar . GetVersion (),
2023-04-21 06:50:53 -04:00
[] string { "Name" , "Description" , "SessionMaxSeconds" , "SessionConnectionLimit" , "DefaultPort" , "DefaultClientPort" })
2020-09-01 15:05:46 -07:00
require . NoError ( t , err , "Failed to reset target." )
}
2021-04-23 09:13:37 -05:00
hCreated := tar . GetCreateTime (). GetTimestamp (). AsTime ()
2020-09-01 15:05:46 -07:00
toMerge := & pbs . UpdateTargetRequest {
Id : tar . GetPublicId (),
}
2022-06-15 08:56:24 -07:00
tested , err := testService ( t , context . Background (), conn , kms , wrapper )
2020-09-01 15:05:46 -07:00
require . NoError ( t , err , "Failed to create a new host set service." )
2025-01-08 15:18:03 +00:00
// Ensure we are using the OSS worker filter functions. This prevents us
// from running tests in parallel.
server . TestUseCommunityFilterWorkersFn ( t )
2022-11-30 15:23:37 -05:00
validateIngressFn := targets . ValidateIngressWorkerFilterFn
targets . ValidateIngressWorkerFilterFn = targets . IngressWorkerFilterUnsupported
2020-09-01 15:05:46 -07:00
cases := [] struct {
2020-09-23 08:10:27 -07:00
name string
req * pbs . UpdateTargetRequest
res * pbs . UpdateTargetResponse
err error
2020-09-01 15:05:46 -07:00
}{
{
name : "Update an Existing Target" ,
req : & pbs . UpdateTargetRequest {
UpdateMask : & field_mask . FieldMask {
2020-09-23 08:30:25 -07:00
Paths : [] string { "name" , "description" , "session_max_seconds" , "session_connection_limit" , "type" },
2020-09-01 15:05:46 -07:00
},
Item : & pb . Target {
2020-09-19 14:01:49 -04:00
Name : wrapperspb . String ( "name" ),
Description : wrapperspb . String ( "desc" ),
SessionMaxSeconds : wrapperspb . UInt32 ( 3600 ),
2020-09-20 15:53:49 -04:00
SessionConnectionLimit : wrapperspb . Int32 ( 5 ),
2023-11-02 16:03:47 -04:00
Type : tcp . Subtype . String (),
2020-09-01 15:05:46 -07:00
},
},
res : & pbs . UpdateTargetResponse {
Item : & pb . Target {
Id : tar . GetPublicId (),
2022-07-20 16:24:46 -07:00
ScopeId : tar . GetProjectId (),
2021-03-25 03:15:43 -04:00
Scope : & scopes . ScopeInfo { Id : proj . GetPublicId (), Type : scope . Project . String (), ParentScopeId : org . GetPublicId ()},
2020-09-01 15:05:46 -07:00
Name : wrapperspb . String ( "name" ),
Description : wrapperspb . String ( "desc" ),
2023-11-02 16:03:47 -04:00
Type : tcp . Subtype . String (),
2022-04-13 16:27:48 -04:00
Attrs : & pb . Target_TcpTargetAttributes {
TcpTargetAttributes : & pb . TcpTargetAttributes {
2023-04-21 06:50:53 -04:00
DefaultPort : wrapperspb . UInt32 ( 2 ),
DefaultClientPort : wrapperspb . UInt32 ( 3 ),
2022-04-13 16:27:48 -04:00
},
},
2020-09-19 14:01:49 -04:00
CreatedTime : tar . GetCreateTime (). GetTimestamp (),
2021-07-30 08:48:03 -04:00
HostSourceIds : hostSourceIds ,
HostSources : hostSources ,
2020-09-19 14:01:49 -04:00
SessionMaxSeconds : wrapperspb . UInt32 ( 3600 ),
2020-09-20 15:53:49 -04:00
SessionConnectionLimit : wrapperspb . Int32 ( 5 ),
2021-04-23 09:13:37 -05:00
AuthorizedActions : testAuthorizedActions ,
2022-12-06 12:33:28 -08:00
Address : & wrapperspb . StringValue {},
2020-09-01 15:05:46 -07:00
},
},
},
{
name : "Multiple Paths in single string" ,
req : & pbs . UpdateTargetRequest {
UpdateMask : & field_mask . FieldMask {
2020-09-23 08:30:25 -07:00
Paths : [] string { "name,description,type" },
2020-09-01 15:05:46 -07:00
},
Item : & pb . Target {
Name : wrapperspb . String ( "name" ),
Description : wrapperspb . String ( "desc" ),
2023-11-02 16:03:47 -04:00
Type : tcp . Subtype . String (),
2020-09-01 15:05:46 -07:00
},
},
res : & pbs . UpdateTargetResponse {
Item : & pb . Target {
Id : tar . GetPublicId (),
2022-07-20 16:24:46 -07:00
ScopeId : tar . GetProjectId (),
2021-03-25 03:15:43 -04:00
Scope : & scopes . ScopeInfo { Id : proj . GetPublicId (), Type : scope . Project . String (), ParentScopeId : org . GetPublicId ()},
2020-09-01 15:05:46 -07:00
Name : wrapperspb . String ( "name" ),
Description : wrapperspb . String ( "desc" ),
CreatedTime : tar . GetCreateTime (). GetTimestamp (),
2023-11-02 16:03:47 -04:00
Type : tcp . Subtype . String (),
2022-04-13 16:27:48 -04:00
Attrs : & pb . Target_TcpTargetAttributes {
TcpTargetAttributes : & pb . TcpTargetAttributes {
2023-04-21 06:50:53 -04:00
DefaultPort : wrapperspb . UInt32 ( 2 ),
DefaultClientPort : wrapperspb . UInt32 ( 3 ),
2022-04-13 16:27:48 -04:00
},
},
2021-07-30 08:48:03 -04:00
HostSourceIds : hostSourceIds ,
HostSources : hostSources ,
2022-06-13 08:26:24 -07:00
SessionMaxSeconds : wrapperspb . UInt32 ( tar . GetSessionMaxSeconds ()),
SessionConnectionLimit : wrapperspb . Int32 ( tar . GetSessionConnectionLimit ()),
2021-04-23 09:13:37 -05:00
AuthorizedActions : testAuthorizedActions ,
2022-12-06 12:33:28 -08:00
Address : & wrapperspb . StringValue {},
2020-09-01 15:05:46 -07:00
},
},
},
{
name : "No Update Mask" ,
req : & pbs . UpdateTargetRequest {
Item : & pb . Target {
Name : wrapperspb . String ( "updated name" ),
Description : wrapperspb . String ( "updated desc" ),
},
},
2020-09-23 08:10:27 -07:00
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
{
name : "Empty Path" ,
req : & pbs . UpdateTargetRequest {
UpdateMask : & field_mask . FieldMask { Paths : [] string {}},
Item : & pb . Target {
Name : wrapperspb . String ( "updated name" ),
Description : wrapperspb . String ( "updated desc" ),
},
},
2020-09-23 08:10:27 -07:00
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
{
name : "Update port to 0" ,
req : & pbs . UpdateTargetRequest {
2022-06-13 08:26:24 -07:00
UpdateMask : & field_mask . FieldMask { Paths : [] string { "attributes.default_port" }},
2020-09-01 15:05:46 -07:00
Item : & pb . Target {
2022-04-13 16:27:48 -04:00
Attrs : & pb . Target_TcpTargetAttributes {
TcpTargetAttributes : & pb . TcpTargetAttributes {
2023-04-21 06:50:53 -04:00
DefaultPort : wrapperspb . UInt32 ( 0 ),
DefaultClientPort : wrapperspb . UInt32 ( 3 ),
2022-04-13 16:27:48 -04:00
},
},
2020-09-01 15:05:46 -07:00
},
},
2020-09-23 08:10:27 -07:00
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
2022-06-13 08:26:24 -07:00
{
name : "Clear port" ,
req : & pbs . UpdateTargetRequest {
UpdateMask : & field_mask . FieldMask { Paths : [] string { "attributes.default_port" }},
Item : & pb . Target {},
},
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
2020-09-01 15:05:46 -07:00
{
2024-02-16 08:30:16 -05:00
name : "Only non-existent paths in Mask" ,
2020-09-01 15:05:46 -07:00
req : & pbs . UpdateTargetRequest {
2024-02-16 08:30:16 -05:00
UpdateMask : & field_mask . FieldMask { Paths : [] string { "nonexistent_field" }},
2020-09-01 15:05:46 -07:00
Item : & pb . Target {
Name : wrapperspb . String ( "updated name" ),
Description : wrapperspb . String ( "updated desc" ),
},
},
2020-09-23 08:10:27 -07:00
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
{
name : "Unset Name" ,
req : & pbs . UpdateTargetRequest {
UpdateMask : & field_mask . FieldMask {
Paths : [] string { "name" },
},
Item : & pb . Target {
Description : wrapperspb . String ( "ignored" ),
},
},
2020-09-23 08:10:27 -07:00
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
{
name : "Unset Description" ,
req : & pbs . UpdateTargetRequest {
UpdateMask : & field_mask . FieldMask {
Paths : [] string { "description" },
},
Item : & pb . Target {
Name : wrapperspb . String ( "ignored" ),
},
},
res : & pbs . UpdateTargetResponse {
Item : & pb . Target {
Id : tar . GetPublicId (),
2022-07-20 16:24:46 -07:00
ScopeId : tar . GetProjectId (),
2021-03-25 03:15:43 -04:00
Scope : & scopes . ScopeInfo { Id : proj . GetPublicId (), Type : scope . Project . String (), ParentScopeId : org . GetPublicId ()},
2020-09-01 15:05:46 -07:00
Name : wrapperspb . String ( "default" ),
CreatedTime : tar . GetCreateTime (). GetTimestamp (),
2023-11-02 16:03:47 -04:00
Type : tcp . Subtype . String (),
2022-04-13 16:27:48 -04:00
Attrs : & pb . Target_TcpTargetAttributes {
TcpTargetAttributes : & pb . TcpTargetAttributes {
2023-04-21 06:50:53 -04:00
DefaultPort : wrapperspb . UInt32 ( 2 ),
DefaultClientPort : wrapperspb . UInt32 ( 3 ),
2022-04-13 16:27:48 -04:00
},
},
2021-07-30 08:48:03 -04:00
HostSourceIds : hostSourceIds ,
HostSources : hostSources ,
2022-06-13 08:26:24 -07:00
SessionMaxSeconds : wrapperspb . UInt32 ( tar . GetSessionMaxSeconds ()),
SessionConnectionLimit : wrapperspb . Int32 ( tar . GetSessionConnectionLimit ()),
2021-04-23 09:13:37 -05:00
AuthorizedActions : testAuthorizedActions ,
2022-12-06 12:33:28 -08:00
Address : & wrapperspb . StringValue {},
2020-09-01 15:05:46 -07:00
},
},
},
{
name : "Update Only Name" ,
req : & pbs . UpdateTargetRequest {
UpdateMask : & field_mask . FieldMask {
Paths : [] string { "name" },
},
Item : & pb . Target {
Name : wrapperspb . String ( "updated" ),
Description : wrapperspb . String ( "ignored" ),
},
},
res : & pbs . UpdateTargetResponse {
Item : & pb . Target {
Id : tar . GetPublicId (),
2022-07-20 16:24:46 -07:00
ScopeId : tar . GetProjectId (),
2021-03-25 03:15:43 -04:00
Scope : & scopes . ScopeInfo { Id : proj . GetPublicId (), Type : scope . Project . String (), ParentScopeId : org . GetPublicId ()},
2020-09-01 15:05:46 -07:00
Name : wrapperspb . String ( "updated" ),
Description : wrapperspb . String ( "default" ),
CreatedTime : tar . GetCreateTime (). GetTimestamp (),
2023-11-02 16:03:47 -04:00
Type : tcp . Subtype . String (),
2022-04-13 16:27:48 -04:00
Attrs : & pb . Target_TcpTargetAttributes {
TcpTargetAttributes : & pb . TcpTargetAttributes {
2023-04-21 06:50:53 -04:00
DefaultPort : wrapperspb . UInt32 ( 2 ),
DefaultClientPort : wrapperspb . UInt32 ( 3 ),
2022-04-13 16:27:48 -04:00
},
},
2021-07-30 08:48:03 -04:00
HostSourceIds : hostSourceIds ,
HostSources : hostSources ,
2022-06-13 08:26:24 -07:00
SessionMaxSeconds : wrapperspb . UInt32 ( tar . GetSessionMaxSeconds ()),
SessionConnectionLimit : wrapperspb . Int32 ( tar . GetSessionConnectionLimit ()),
2021-04-23 09:13:37 -05:00
AuthorizedActions : testAuthorizedActions ,
2022-12-06 12:33:28 -08:00
Address : & wrapperspb . StringValue {},
2020-09-01 15:05:46 -07:00
},
},
},
{
name : "Update Only Description" ,
req : & pbs . UpdateTargetRequest {
UpdateMask : & field_mask . FieldMask {
Paths : [] string { "description" },
},
Item : & pb . Target {
Name : wrapperspb . String ( "ignored" ),
Description : wrapperspb . String ( "notignored" ),
},
},
res : & pbs . UpdateTargetResponse {
Item : & pb . Target {
Id : tar . GetPublicId (),
2022-07-20 16:24:46 -07:00
ScopeId : tar . GetProjectId (),
2021-03-25 03:15:43 -04:00
Scope : & scopes . ScopeInfo { Id : proj . GetPublicId (), Type : scope . Project . String (), ParentScopeId : org . GetPublicId ()},
2020-09-01 15:05:46 -07:00
Name : wrapperspb . String ( "default" ),
Description : wrapperspb . String ( "notignored" ),
CreatedTime : tar . GetCreateTime (). GetTimestamp (),
2022-04-13 16:27:48 -04:00
Attrs : & pb . Target_TcpTargetAttributes {
TcpTargetAttributes : & pb . TcpTargetAttributes {
2023-04-21 06:50:53 -04:00
DefaultPort : wrapperspb . UInt32 ( 2 ),
DefaultClientPort : wrapperspb . UInt32 ( 3 ),
2022-04-13 16:27:48 -04:00
},
},
2023-11-02 16:03:47 -04:00
Type : tcp . Subtype . String (),
2021-07-30 08:48:03 -04:00
HostSourceIds : hostSourceIds ,
HostSources : hostSources ,
2022-06-13 08:26:24 -07:00
SessionMaxSeconds : wrapperspb . UInt32 ( tar . GetSessionMaxSeconds ()),
SessionConnectionLimit : wrapperspb . Int32 ( tar . GetSessionConnectionLimit ()),
2021-04-23 09:13:37 -05:00
AuthorizedActions : testAuthorizedActions ,
2022-12-06 12:33:28 -08:00
Address : & wrapperspb . StringValue {},
2020-09-01 15:05:46 -07:00
},
},
},
2024-03-12 13:57:47 -07:00
{
name : "Update WithAlias" ,
req : & pbs . UpdateTargetRequest {
UpdateMask : & field_mask . FieldMask {
Paths : [] string { "with_alias" },
},
Item : & pb . Target {
Name : wrapperspb . String ( "ignored" ),
WithAliases : [] * pb . Alias {{ Value : "new-alias" , ScopeId : "global" }},
},
},
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
2020-09-01 15:05:46 -07:00
{
name : "Update a Non Existing Target" ,
req : & pbs . UpdateTargetRequest {
2023-03-10 15:06:39 -05:00
Id : globals . TcpTargetPrefix + "_DoesntExis" ,
2020-09-01 15:05:46 -07:00
UpdateMask : & field_mask . FieldMask {
Paths : [] string { "description" },
},
Item : & pb . Target {
Name : wrapperspb . String ( "new" ),
2021-03-25 03:15:43 -04:00
Scope : & scopes . ScopeInfo { Id : proj . GetPublicId (), Type : scope . Project . String (), ParentScopeId : org . GetPublicId ()},
2020-09-01 15:05:46 -07:00
Description : wrapperspb . String ( "desc" ),
},
},
2020-09-23 08:10:27 -07:00
err : handlers . ApiErrorWithCode ( codes . NotFound ),
2020-09-01 15:05:46 -07:00
},
{
name : "Cant change Id" ,
req : & pbs . UpdateTargetRequest {
Id : hc . GetPublicId (),
UpdateMask : & field_mask . FieldMask {
Paths : [] string { "id" },
},
Item : & pb . Target {
Id : "p_somethinge" ,
2021-03-25 03:15:43 -04:00
Scope : & scopes . ScopeInfo { Id : proj . GetPublicId (), Type : scope . Project . String (), ParentScopeId : org . GetPublicId ()},
2020-09-01 15:05:46 -07:00
Name : wrapperspb . String ( "new" ),
Description : wrapperspb . String ( "new desc" ),
2021-01-07 10:02:32 -05:00
},
},
2020-09-23 08:10:27 -07:00
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
{
name : "Cant specify Created Time" ,
req : & pbs . UpdateTargetRequest {
UpdateMask : & field_mask . FieldMask {
Paths : [] string { "created_time" },
},
Item : & pb . Target {
2021-04-23 09:13:37 -05:00
CreatedTime : timestamppb . Now (),
2020-09-01 15:05:46 -07:00
},
},
2020-09-23 08:10:27 -07:00
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
{
name : "Cant specify Updated Time" ,
req : & pbs . UpdateTargetRequest {
UpdateMask : & field_mask . FieldMask {
Paths : [] string { "updated_time" },
},
Item : & pb . Target {
2021-04-23 09:13:37 -05:00
UpdatedTime : timestamppb . Now (),
2020-09-01 15:05:46 -07:00
},
},
2020-09-23 08:10:27 -07:00
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
2020-09-01 15:05:46 -07:00
},
2022-11-30 15:23:37 -05:00
{
name : "Ingress filter unsupported" ,
req : & pbs . UpdateTargetRequest {
UpdateMask : & field_mask . FieldMask {
Paths : [] string { "ingress_worker_filter" },
},
Item : & pb . Target {
IngressWorkerFilter : wrapperspb . String ( `type == "bar"` ),
},
},
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
name : "Can't update worker filter and egress filter" ,
req : & pbs . UpdateTargetRequest {
UpdateMask : & field_mask . FieldMask {
Paths : [] string { "worker_filter" , "egress_worker_filter" },
},
Item : & pb . Target {
WorkerFilter : wrapperspb . String ( `type == "bar"` ),
EgressWorkerFilter : wrapperspb . String ( `type == "bar"` ),
},
},
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
2022-12-06 12:33:28 -08:00
{
name : "Invalid address length" ,
req : & pbs . UpdateTargetRequest {
UpdateMask : & field_mask . FieldMask {
Paths : [] string { "address" },
},
Item : & pb . Target {
Address : wrapperspb . String ( "ab" ),
},
},
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
name : "Invalid address w/ port" ,
req : & pbs . UpdateTargetRequest {
UpdateMask : & field_mask . FieldMask {
Paths : [] string { "address" },
},
Item : & pb . Target {
Address : wrapperspb . String ( "8.8.8.8:80" ),
},
},
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
name : "Invalid address not parsable" ,
req : & pbs . UpdateTargetRequest {
UpdateMask : & field_mask . FieldMask {
Paths : [] string { "address" },
},
Item : & pb . Target {
Address : wrapperspb . String ( "aaa.8bc.8.8:80:abc" ),
},
},
res : nil ,
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
2020-09-01 15:05:46 -07:00
}
for _ , tc := range cases {
t . Run ( tc . name , func ( t * testing . T ) {
2022-06-13 08:26:24 -07:00
defer resetTarget ()
2020-09-01 15:05:46 -07:00
assert , require := assert . New ( t ), require . New ( t )
2022-06-13 08:26:24 -07:00
tc . req . Item . Version = tar . GetVersion ()
2020-09-01 15:05:46 -07:00
req := proto . Clone ( toMerge ).( * pbs . UpdateTargetRequest )
proto . Merge ( req , tc . req )
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx := auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
got , gErr := tested . UpdateTarget ( ctx , req )
2020-09-23 08:10:27 -07:00
if tc . err != nil {
require . Error ( gErr )
assert . True ( errors . Is ( gErr , tc . err ), "UpdateTarget(%+v) got error %v, wanted %v" , req , gErr , tc . err )
2022-06-13 08:26:24 -07:00
return
2020-09-23 08:10:27 -07:00
}
2022-06-13 08:26:24 -07:00
require . NoError ( gErr )
2020-09-01 15:05:46 -07:00
if got != nil {
assert . NotNilf ( tc . res , "Expected UpdateHost response to be nil, but was %v" , got )
2021-04-23 09:13:37 -05:00
gotUpdateTime := got . GetItem (). GetUpdatedTime (). AsTime ()
2020-09-01 15:05:46 -07:00
// Verify it is a set updated after it was created
// TODO: This is currently failing.
assert . True ( gotUpdateTime . After ( hCreated ), "Updated target should have been updated after it's creation. Was updated %v, which is after %v" , gotUpdateTime , hCreated )
// Clear all values which are hard to compare against.
got . Item . UpdatedTime , tc . res . Item . UpdatedTime = nil , nil
}
if tc . res != nil {
2022-06-13 08:26:24 -07:00
tc . res . Item . Version = tc . req . Item . Version + 1
2020-09-01 15:05:46 -07:00
}
2023-10-31 13:44:17 +00:00
assert . Empty ( cmp . Diff (
got ,
tc . res ,
protocmp . Transform (),
cmpopts . SortSlices ( func ( a , b string ) bool {
return a < b
}),
), "UpdateTarget(%q) got response %q, wanted %q" , req , got , tc . res )
2020-09-01 15:05:46 -07:00
})
}
2022-11-30 15:23:37 -05:00
// Reset worker filter funcs
targets . ValidateIngressWorkerFilterFn = validateIngressFn
2020-09-01 15:05:46 -07:00
}
2020-09-25 13:41:20 -07:00
func TestUpdate_BadVersion ( t * testing . T ) {
t . Parallel ()
2023-06-06 17:09:08 -04:00
ctx := context . Background ()
2020-09-25 13:41:20 -07:00
conn , _ := db . TestSetup ( t , "postgres" )
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
2022-07-29 17:24:39 +00:00
rw := db . New ( conn )
2021-03-25 03:15:43 -04:00
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
2022-07-29 17:24:39 +00:00
tokenRepoFn := func () ( * authtoken . Repository , error ) {
2023-06-06 17:09:08 -04:00
return authtoken . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
2021-03-25 03:15:43 -04:00
2022-07-29 17:24:39 +00:00
org , proj := iam . TestScopes ( t , iamRepo )
at := authtoken . TestAuthToken ( t , conn , kms , org . GetPublicId ())
r := iam . TestRole ( t , conn , proj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2020-09-25 13:41:20 -07:00
2022-08-23 17:27:56 +01:00
repoFn := func ( o ... target . Option ) ( * target . Repository , error ) {
2022-08-23 18:44:10 +01:00
return target . NewRepository ( ctx , rw , rw , kms )
2020-09-25 13:41:20 -07:00
}
repo , err := repoFn ()
require . NoError ( t , err , "Couldn't create new target repo." )
2023-11-02 16:03:47 -04:00
ttar , err := target . New ( ctx , tcp . Subtype , proj . GetPublicId (), target . WithName ( "default" ), target . WithDescription ( "default" ))
2021-11-04 11:44:22 -04:00
tar := ttar .( * tcp . Target )
2020-09-25 13:41:20 -07:00
tar . DefaultPort = 2
2023-04-21 06:50:53 -04:00
tar . DefaultClientPort = 3
2020-09-25 13:41:20 -07:00
require . NoError ( t , err )
2023-03-30 15:19:30 -04:00
gtar , err := repo . CreateTarget ( context . Background (), tar )
2020-09-25 13:41:20 -07:00
require . NoError ( t , err )
2022-06-15 08:56:24 -07:00
tested , err := testService ( t , context . Background (), conn , kms , wrapper )
2020-09-25 13:41:20 -07:00
require . NoError ( t , err , "Failed to create a new host set service." )
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx = auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
upTar , err := tested . UpdateTarget ( ctx , & pbs . UpdateTargetRequest {
2020-10-06 13:17:28 -04:00
Id : gtar . GetPublicId (),
Item : & pb . Target {
Description : wrapperspb . String ( "updated" ),
Version : 72 ,
2020-09-25 13:41:20 -07:00
},
UpdateMask : & field_mask . FieldMask { Paths : [] string { "description" }},
})
assert . Nil ( t , upTar )
assert . Error ( t , err )
assert . True ( t , errors . Is ( err , handlers . NotFoundError ()), "Got %v, wanted not found error." , err )
}
2021-07-30 08:48:03 -04:00
func TestAddTargetHostSources ( t * testing . T ) {
2023-08-28 15:08:20 -07:00
t . Parallel ()
2023-06-06 17:09:08 -04:00
ctx := context . Background ()
2021-07-30 08:48:03 -04:00
conn , _ := db . TestSetup ( t , "postgres" )
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
2021-11-01 09:07:56 -07:00
sche := scheduler . TestScheduler ( t , conn , wrapper )
2021-07-30 08:48:03 -04:00
2022-07-29 17:24:39 +00:00
rw := db . New ( conn )
2021-07-30 08:48:03 -04:00
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
2022-07-29 17:24:39 +00:00
tokenRepoFn := func () ( * authtoken . Repository , error ) {
2023-06-06 17:09:08 -04:00
return authtoken . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
2021-07-30 08:48:03 -04:00
2022-07-29 17:24:39 +00:00
org , proj := iam . TestScopes ( t , iamRepo )
at := authtoken . TestAuthToken ( t , conn , kms , org . GetPublicId ())
r := iam . TestRole ( t , conn , proj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2021-07-30 08:48:03 -04:00
2022-06-15 08:56:24 -07:00
s , err := testService ( t , context . Background (), conn , kms , wrapper )
2021-07-30 08:48:03 -04:00
require . NoError ( t , err , "Error when getting new target service." )
hc := static . TestCatalogs ( t , conn , proj . GetPublicId (), 1 )[ 0 ]
hs := static . TestSets ( t , conn , hc . GetPublicId (), 2 )
2023-04-24 19:27:41 -04:00
plg := plugin . TestPlugin ( t , conn , "test" )
pluginHc := hostplugin . TestCatalog ( t , conn , proj . GetPublicId (), plg . GetPublicId ())
pluginHs := hostplugin . TestSet ( t , conn , kms , sche , pluginHc , map [ string ] plgpb . HostPluginServiceClient {
2023-04-18 21:12:05 -07:00
plg . GetPublicId (): loopback . NewWrappingPluginHostClient ( & loopback . TestPluginServer {}),
2021-09-21 09:18:49 -07:00
})
2021-09-13 16:22:11 -07:00
2021-07-30 08:48:03 -04:00
addCases := [] struct {
name string
2024-02-13 09:17:41 -08:00
tar target . Target
2021-07-30 08:48:03 -04:00
addHostSources [] string
resultHostSources [] string
}{
{
name : "Add set on empty target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "empty" ),
2021-07-30 08:48:03 -04:00
addHostSources : [] string { hs [ 1 ]. GetPublicId ()},
resultHostSources : [] string { hs [ 1 ]. GetPublicId ()},
},
{
name : "Add set on populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "populated" , target . WithHostSources ([] string { hs [ 0 ]. GetPublicId ()})),
2021-07-30 08:48:03 -04:00
addHostSources : [] string { hs [ 1 ]. GetPublicId ()},
resultHostSources : [] string { hs [ 0 ]. GetPublicId (), hs [ 1 ]. GetPublicId ()},
},
{
name : "Add duplicated sets on populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "duplicated" , target . WithHostSources ([] string { hs [ 0 ]. GetPublicId ()})),
2021-07-30 08:48:03 -04:00
addHostSources : [] string { hs [ 1 ]. GetPublicId (), hs [ 1 ]. GetPublicId ()},
resultHostSources : [] string { hs [ 0 ]. GetPublicId (), hs [ 1 ]. GetPublicId ()},
},
2021-09-13 16:22:11 -07:00
{
name : "Add plugin set on empty target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "plugin empty" ),
2021-09-13 16:22:11 -07:00
addHostSources : [] string { pluginHs . GetPublicId ()},
resultHostSources : [] string { pluginHs . GetPublicId ()},
},
{
name : "Add plugin set on populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "plugin populated" , target . WithHostSources ([] string { hs [ 0 ]. GetPublicId ()})),
2021-09-13 16:22:11 -07:00
addHostSources : [] string { pluginHs . GetPublicId ()},
resultHostSources : [] string { hs [ 0 ]. GetPublicId (), pluginHs . GetPublicId ()},
},
2021-07-30 08:48:03 -04:00
}
for _ , tc := range addCases {
t . Run ( tc . name , func ( t * testing . T ) {
req := & pbs . AddTargetHostSourcesRequest {
2024-02-13 09:17:41 -08:00
Id : tc . tar . GetPublicId (),
Version : tc . tar . GetVersion (),
2021-07-30 08:48:03 -04:00
HostSourceIds : tc . addHostSources ,
}
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx = auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
got , err := s . AddTargetHostSources ( ctx , req )
2021-07-30 08:48:03 -04:00
s , ok := status . FromError ( err )
require . True ( t , ok )
require . NoError ( t , err , "Got error: %v" , s )
assert . ElementsMatch ( t , tc . resultHostSources , got . GetItem (). GetHostSourceIds ())
})
}
2021-11-04 11:44:22 -04:00
tar := tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "test" )
2021-07-30 08:48:03 -04:00
failCases := [] struct {
name string
req * pbs . AddTargetHostSourcesRequest
err error
}{
{
2024-02-01 08:58:56 -08:00
name : "Bad Target Id" ,
2021-07-30 08:48:03 -04:00
req : & pbs . AddTargetHostSourcesRequest {
2024-02-13 09:17:41 -08:00
Id : "bad id" ,
2021-07-30 08:48:03 -04:00
Version : tar . GetVersion (),
HostSourceIds : [] string { hs [ 0 ]. GetPublicId ()},
},
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
name : "Bad version" ,
req : & pbs . AddTargetHostSourcesRequest {
Id : tar . GetPublicId (),
Version : tar . GetVersion () + 2 ,
HostSourceIds : [] string { hs [ 0 ]. GetPublicId ()},
},
err : handlers . ApiErrorWithCode ( codes . Internal ),
},
{
name : "Empty host set list" ,
req : & pbs . AddTargetHostSourcesRequest {
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
},
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
name : "Incorrect host set ids" ,
req : & pbs . AddTargetHostSourcesRequest {
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
HostSourceIds : [] string { "incorrect" },
},
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 )
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx = auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
_ , gErr := s . AddTargetHostSources ( ctx , tc . req )
2021-07-30 08:48:03 -04:00
if tc . err != nil {
require . Error ( gErr )
assert . True ( errors . Is ( gErr , tc . err ), "AddTargetHostSources(%+v) got error %v, wanted %v" , tc . req , gErr , tc . err )
}
})
}
}
func TestSetTargetHostSources ( t * testing . T ) {
2023-08-28 15:08:20 -07:00
t . Parallel ()
2023-06-06 17:09:08 -04:00
ctx := context . Background ()
2021-07-30 08:48:03 -04:00
conn , _ := db . TestSetup ( t , "postgres" )
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
2021-11-01 09:07:56 -07:00
sche := scheduler . TestScheduler ( t , conn , wrapper )
2021-07-30 08:48:03 -04:00
2022-07-29 17:24:39 +00:00
rw := db . New ( conn )
2021-07-30 08:48:03 -04:00
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
2022-07-29 17:24:39 +00:00
tokenRepoFn := func () ( * authtoken . Repository , error ) {
2023-06-06 17:09:08 -04:00
return authtoken . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
2021-07-30 08:48:03 -04:00
2022-07-29 17:24:39 +00:00
org , proj := iam . TestScopes ( t , iamRepo )
at := authtoken . TestAuthToken ( t , conn , kms , org . GetPublicId ())
r := iam . TestRole ( t , conn , proj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2021-07-30 08:48:03 -04:00
2022-06-15 08:56:24 -07:00
s , err := testService ( t , context . Background (), conn , kms , wrapper )
2021-07-30 08:48:03 -04:00
require . NoError ( t , err , "Error when getting new host set service." )
hc := static . TestCatalogs ( t , conn , proj . GetPublicId (), 1 )[ 0 ]
hs := static . TestSets ( t , conn , hc . GetPublicId (), 2 )
2023-04-24 19:27:41 -04:00
plg := plugin . TestPlugin ( t , conn , "test" )
pluginHc := hostplugin . TestCatalog ( t , conn , proj . GetPublicId (), plg . GetPublicId ())
pluginHs := hostplugin . TestSet ( t , conn , kms , sche , pluginHc , map [ string ] plgpb . HostPluginServiceClient {
2023-04-18 21:12:05 -07:00
plg . GetPublicId (): loopback . NewWrappingPluginHostClient ( & loopback . TestPluginServer {}),
2021-09-21 09:18:49 -07:00
})
2021-09-13 16:22:11 -07:00
2021-07-30 08:48:03 -04:00
setCases := [] struct {
name string
2024-02-13 09:17:41 -08:00
tar target . Target
2021-07-30 08:48:03 -04:00
setHostSources [] string
resultHostSources [] string
}{
{
name : "Set on empty target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "empty" ),
2021-07-30 08:48:03 -04:00
setHostSources : [] string { hs [ 1 ]. GetPublicId ()},
resultHostSources : [] string { hs [ 1 ]. GetPublicId ()},
},
{
name : "Set on populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "populated" , target . WithHostSources ([] string { hs [ 0 ]. GetPublicId ()})),
2021-07-30 08:48:03 -04:00
setHostSources : [] string { hs [ 1 ]. GetPublicId ()},
resultHostSources : [] string { hs [ 1 ]. GetPublicId ()},
},
2021-09-13 16:22:11 -07:00
{
name : "Set plugin set on populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "plugin populated" , target . WithHostSources ([] string { hs [ 0 ]. GetPublicId ()})),
2021-09-13 16:22:11 -07:00
setHostSources : [] string { pluginHs . GetPublicId ()},
resultHostSources : [] string { pluginHs . GetPublicId ()},
},
2021-07-30 08:48:03 -04:00
{
name : "Set duplicate host set on populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "duplicate" , target . WithHostSources ([] string { hs [ 0 ]. GetPublicId ()})),
2021-07-30 08:48:03 -04:00
setHostSources : [] string { hs [ 1 ]. GetPublicId (), hs [ 1 ]. GetPublicId ()},
resultHostSources : [] string { hs [ 1 ]. GetPublicId ()},
},
{
name : "Set empty on populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "another populated" , target . WithHostSources ([] string { hs [ 0 ]. GetPublicId ()})),
2021-07-30 08:48:03 -04:00
setHostSources : [] string {},
resultHostSources : nil ,
},
}
for _ , tc := range setCases {
t . Run ( tc . name , func ( t * testing . T ) {
req := & pbs . SetTargetHostSourcesRequest {
2024-02-13 09:17:41 -08:00
Id : tc . tar . GetPublicId (),
Version : tc . tar . GetVersion (),
2021-07-30 08:48:03 -04:00
HostSourceIds : tc . setHostSources ,
}
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx = auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
got , err := s . SetTargetHostSources ( ctx , req )
2021-07-30 08:48:03 -04:00
require . NoError ( t , err , "Got error: %v" , s )
assert . ElementsMatch ( t , tc . resultHostSources , got . GetItem (). GetHostSourceIds ())
})
}
2021-11-04 11:44:22 -04:00
tar := tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "test name" )
2021-07-30 08:48:03 -04:00
failCases := [] struct {
name string
req * pbs . SetTargetHostSourcesRequest
err error
}{
{
name : "Bad target Id" ,
req : & pbs . SetTargetHostSourcesRequest {
2024-02-13 09:17:41 -08:00
Id : "bad id" ,
2021-07-30 08:48:03 -04:00
Version : tar . GetVersion (),
HostSourceIds : [] string { hs [ 0 ]. GetPublicId ()},
},
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
name : "Bad version" ,
req : & pbs . SetTargetHostSourcesRequest {
Id : tar . GetPublicId (),
Version : tar . GetVersion () + 3 ,
HostSourceIds : [] string { hs [ 0 ]. GetPublicId ()},
},
err : handlers . ApiErrorWithCode ( codes . Internal ),
},
{
name : "Bad host set id" ,
req : & pbs . SetTargetHostSourcesRequest {
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
HostSourceIds : [] 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 )
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx = auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
_ , gErr := s . SetTargetHostSources ( ctx , tc . req )
2021-07-30 08:48:03 -04:00
if tc . err != nil {
require . Error ( gErr )
assert . True ( errors . Is ( gErr , tc . err ), "SetTargetHostSources(%+v) got error %v, wanted %v" , tc . req , gErr , tc . err )
}
})
}
}
func TestRemoveTargetHostSources ( t * testing . T ) {
2023-08-28 15:08:20 -07:00
t . Parallel ()
2023-06-06 17:09:08 -04:00
ctx := context . Background ()
2021-07-30 08:48:03 -04:00
conn , _ := db . TestSetup ( t , "postgres" )
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
2021-11-01 09:07:56 -07:00
sche := scheduler . TestScheduler ( t , conn , wrapper )
2021-07-30 08:48:03 -04:00
2022-07-29 17:24:39 +00:00
rw := db . New ( conn )
2021-07-30 08:48:03 -04:00
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
2022-07-29 17:24:39 +00:00
tokenRepoFn := func () ( * authtoken . Repository , error ) {
2023-06-06 17:09:08 -04:00
return authtoken . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
2021-07-30 08:48:03 -04:00
2022-07-29 17:24:39 +00:00
org , proj := iam . TestScopes ( t , iamRepo )
at := authtoken . TestAuthToken ( t , conn , kms , org . GetPublicId ())
r := iam . TestRole ( t , conn , proj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2021-07-30 08:48:03 -04:00
2022-06-15 08:56:24 -07:00
s , err := testService ( t , context . Background (), conn , kms , wrapper )
2021-07-30 08:48:03 -04:00
require . NoError ( t , err , "Error when getting new host set service." )
hc := static . TestCatalogs ( t , conn , proj . GetPublicId (), 1 )[ 0 ]
hs := static . TestSets ( t , conn , hc . GetPublicId (), 2 )
2023-04-24 19:27:41 -04:00
plg := plugin . TestPlugin ( t , conn , "test" )
pluginHc := hostplugin . TestCatalog ( t , conn , proj . GetPublicId (), plg . GetPublicId ())
pluginHs := hostplugin . TestSet ( t , conn , kms , sche , pluginHc , map [ string ] plgpb . HostPluginServiceClient {
2023-04-18 21:12:05 -07:00
plg . GetPublicId (): loopback . NewWrappingPluginHostClient ( & loopback . TestPluginServer {}),
2021-09-21 09:18:49 -07:00
})
2021-09-13 16:22:11 -07:00
2021-07-30 08:48:03 -04:00
removeCases := [] struct {
name string
2024-02-13 09:17:41 -08:00
tar target . Target
2021-07-30 08:48:03 -04:00
removeHostSources [] string
resultHostSources [] string
wantErr bool
}{
{
name : "Remove from empty" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "empty" ),
2021-07-30 08:48:03 -04:00
removeHostSources : [] string { hs [ 1 ]. GetPublicId ()},
wantErr : true ,
},
{
name : "Remove 1 of 2 sets" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "remove partial" , target . WithHostSources ([] string { hs [ 0 ]. GetPublicId (), hs [ 1 ]. GetPublicId ()})),
2021-07-30 08:48:03 -04:00
removeHostSources : [] string { hs [ 1 ]. GetPublicId ()},
resultHostSources : [] string { hs [ 0 ]. GetPublicId ()},
},
2021-09-13 16:22:11 -07:00
{
name : "Remove 1 plugin set of 2 sets" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "remove plugin partial" , target . WithHostSources ([] string { hs [ 0 ]. GetPublicId (), pluginHs . GetPublicId ()})),
2021-09-13 16:22:11 -07:00
removeHostSources : [] string { pluginHs . GetPublicId ()},
resultHostSources : [] string { hs [ 0 ]. GetPublicId ()},
},
2021-07-30 08:48:03 -04:00
{
name : "Remove 1 duplicate set of 2 sets" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "remove duplicate" , target . WithHostSources ([] string { hs [ 0 ]. GetPublicId (), hs [ 1 ]. GetPublicId ()})),
2021-07-30 08:48:03 -04:00
removeHostSources : [] string { hs [ 1 ]. GetPublicId (), hs [ 1 ]. GetPublicId ()},
resultHostSources : [] string { hs [ 0 ]. GetPublicId ()},
},
{
name : "Remove all hosts from set" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "remove all" , target . WithHostSources ([] string { hs [ 0 ]. GetPublicId (), hs [ 1 ]. GetPublicId ()})),
2021-07-30 08:48:03 -04:00
removeHostSources : [] string { hs [ 0 ]. GetPublicId (), hs [ 1 ]. GetPublicId ()},
resultHostSources : [] string {},
},
}
for _ , tc := range removeCases {
t . Run ( tc . name , func ( t * testing . T ) {
req := & pbs . RemoveTargetHostSourcesRequest {
2024-02-13 09:17:41 -08:00
Id : tc . tar . GetPublicId (),
Version : tc . tar . GetVersion (),
2021-07-30 08:48:03 -04:00
HostSourceIds : tc . removeHostSources ,
}
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx = auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
got , err := s . RemoveTargetHostSources ( ctx , req )
2021-07-30 08:48:03 -04:00
if tc . wantErr {
assert . Error ( t , err )
return
}
s , ok := status . FromError ( err )
require . True ( t , ok )
require . NoError ( t , err , "Got error: %v" , s )
assert . ElementsMatch ( t , tc . resultHostSources , got . GetItem (). GetHostSourceIds ())
})
}
2021-11-04 11:44:22 -04:00
tar := tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "testing" )
2021-07-30 08:48:03 -04:00
failCases := [] struct {
name string
req * pbs . RemoveTargetHostSourcesRequest
err error
}{
{
name : "Bad version" ,
req : & pbs . RemoveTargetHostSourcesRequest {
Id : tar . GetPublicId (),
Version : tar . GetVersion () + 3 ,
HostSourceIds : [] string { hs [ 0 ]. GetPublicId ()},
},
err : handlers . ApiErrorWithCode ( codes . Internal ),
},
{
name : "Bad target Id" ,
req : & pbs . RemoveTargetHostSourcesRequest {
2024-02-13 09:17:41 -08:00
Id : "bad id" ,
2021-07-30 08:48:03 -04:00
Version : tar . GetVersion (),
HostSourceIds : [] string { hs [ 0 ]. GetPublicId ()},
},
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
name : "empty sets" ,
req : & pbs . RemoveTargetHostSourcesRequest {
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
HostSourceIds : [] string {},
},
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
name : "Invalid set ids" ,
req : & pbs . RemoveTargetHostSourcesRequest {
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
HostSourceIds : [] 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 )
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx = auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
_ , gErr := s . RemoveTargetHostSources ( ctx , tc . req )
2021-07-30 08:48:03 -04:00
if tc . err != nil {
require . Error ( gErr )
assert . True ( errors . Is ( gErr , tc . err ), "RemoveTargetHostSets(%+v) got error %v, wanted %v" , tc . req , gErr , tc . err )
2020-09-23 08:10:27 -07:00
}
2020-09-01 15:05:46 -07:00
})
}
}
2021-06-22 22:26:26 -04:00
2022-06-08 13:51:56 -07:00
func TestAddTargetCredentialSources ( t * testing . T ) {
2023-08-28 15:08:20 -07:00
t . Parallel ()
2023-06-06 17:09:08 -04:00
ctx := context . Background ()
2021-06-22 22:26:26 -04:00
conn , _ := db . TestSetup ( t , "postgres" )
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
2022-07-29 17:24:39 +00:00
rw := db . New ( conn )
2021-06-22 22:26:26 -04:00
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
2022-07-29 17:24:39 +00:00
tokenRepoFn := func () ( * authtoken . Repository , error ) {
2023-06-06 17:09:08 -04:00
return authtoken . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
2021-06-22 22:26:26 -04:00
2022-07-29 17:24:39 +00:00
org , proj := iam . TestScopes ( t , iamRepo )
at := authtoken . TestAuthToken ( t , conn , kms , org . GetPublicId ())
r := iam . TestRole ( t , conn , proj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2021-06-22 22:26:26 -04:00
2022-06-15 08:56:24 -07:00
s , err := testService ( t , context . Background (), conn , kms , wrapper )
2021-06-22 22:26:26 -04:00
require . NoError ( t , err , "Error when getting new target service." )
2022-06-08 13:51:56 -07:00
storeVault := vault . TestCredentialStores ( t , conn , wrapper , proj . GetPublicId (), 1 )[ 0 ]
cls := vault . TestCredentialLibraries ( t , conn , wrapper , storeVault . GetPublicId (), 2 )
storeStatic := credstatic . TestCredentialStore ( t , conn , wrapper , proj . GetPublicId ())
creds := credstatic . TestUsernamePasswordCredentials ( t , conn , wrapper , "user" , "pass" , storeStatic . GetPublicId (), proj . GetPublicId (), 2 )
2021-06-22 22:26:26 -04:00
addCases := [] struct {
2021-07-27 12:48:36 -04:00
name string
2024-02-13 09:17:41 -08:00
tar target . Target
2021-07-27 12:48:36 -04:00
addSources [] string
resultSourceIds [] string
2021-06-22 22:26:26 -04:00
}{
{
2022-06-08 13:51:56 -07:00
name : "Add library on empty target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "empty for lib sources" ),
2021-07-27 12:48:36 -04:00
addSources : [] string { cls [ 1 ]. GetPublicId ()},
resultSourceIds : [] string { cls [ 1 ]. GetPublicId ()},
2022-06-08 13:51:56 -07:00
},
{
name : "Add static cred on empty target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "empty for static sources" ),
2022-06-08 13:51:56 -07:00
addSources : [] string { creds [ 1 ]. GetPublicId ()},
resultSourceIds : [] string { creds [ 1 ]. GetPublicId ()},
2021-07-27 12:48:36 -04:00
},
{
2022-06-08 13:51:56 -07:00
name : "Add library on library populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "populated for lib-lib sources" , target . WithCredentialLibraries ([] * target . CredentialLibrary { target . TestNewCredentialLibrary ( "" , cls [ 0 ]. GetPublicId (), credential . BrokeredPurpose )})),
2021-07-27 12:48:36 -04:00
addSources : [] string { cls [ 1 ]. GetPublicId ()},
resultSourceIds : [] string { cls [ 0 ]. GetPublicId (), cls [ 1 ]. GetPublicId ()},
},
{
2022-06-08 13:51:56 -07:00
name : "Add library on static cred populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "populated for lib-static sources" , target . WithStaticCredentials ([] * target . StaticCredential { target . TestNewStaticCredential ( "" , creds [ 0 ]. GetPublicId (), credential . BrokeredPurpose )})),
2022-06-08 13:51:56 -07:00
addSources : [] string { cls [ 1 ]. GetPublicId ()},
resultSourceIds : [] string { creds [ 0 ]. GetPublicId (), cls [ 1 ]. GetPublicId ()},
},
{
name : "Add static cred on library populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "populated for static-lib sources" , target . WithCredentialLibraries ([] * target . CredentialLibrary { target . TestNewCredentialLibrary ( "" , cls [ 0 ]. GetPublicId (), credential . BrokeredPurpose )})),
2022-06-08 13:51:56 -07:00
addSources : [] string { creds [ 1 ]. GetPublicId ()},
resultSourceIds : [] string { cls [ 0 ]. GetPublicId (), creds [ 1 ]. GetPublicId ()},
},
{
name : "Add static cred on static cred populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "populated for static-static sources" , target . WithStaticCredentials ([] * target . StaticCredential { target . TestNewStaticCredential ( "" , creds [ 0 ]. GetPublicId (), credential . BrokeredPurpose )})),
2022-06-08 13:51:56 -07:00
addSources : [] string { creds [ 1 ]. GetPublicId ()},
resultSourceIds : [] string { creds [ 0 ]. GetPublicId (), creds [ 1 ]. GetPublicId ()},
2021-06-22 22:26:26 -04:00
},
{
2022-06-08 13:51:56 -07:00
name : "Add duplicated sources on library populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "duplicated for lib sources" , target . WithCredentialLibraries ([] * target . CredentialLibrary { target . TestNewCredentialLibrary ( "" , cls [ 0 ]. GetPublicId (), credential . BrokeredPurpose )})),
2022-06-08 13:51:56 -07:00
addSources : [] string { cls [ 1 ]. GetPublicId (), cls [ 1 ]. GetPublicId (), creds [ 1 ]. GetPublicId (), creds [ 1 ]. GetPublicId ()},
resultSourceIds : [] string { cls [ 0 ]. GetPublicId (), cls [ 1 ]. GetPublicId (), creds [ 1 ]. GetPublicId ()},
2021-06-22 22:26:26 -04:00
},
{
2022-06-08 13:51:56 -07:00
name : "Add duplicated sources on static cred populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "duplicated for static sources" , target . WithStaticCredentials ([] * target . StaticCredential { target . TestNewStaticCredential ( "" , creds [ 0 ]. GetPublicId (), credential . BrokeredPurpose )})),
2022-06-08 13:51:56 -07:00
addSources : [] string { cls [ 1 ]. GetPublicId (), cls [ 1 ]. GetPublicId (), creds [ 1 ]. GetPublicId (), creds [ 1 ]. GetPublicId ()},
resultSourceIds : [] string { creds [ 0 ]. GetPublicId (), cls [ 1 ]. GetPublicId (), creds [ 1 ]. GetPublicId ()},
2021-06-22 22:26:26 -04:00
},
}
for _ , tc := range addCases {
t . Run ( tc . name , func ( t * testing . T ) {
2021-07-27 12:48:36 -04:00
req := & pbs . AddTargetCredentialSourcesRequest {
2024-02-13 09:17:41 -08:00
Id : tc . tar . GetPublicId (),
Version : tc . tar . GetVersion (),
2022-07-19 15:16:24 -07:00
BrokeredCredentialSourceIds : tc . addSources ,
2021-06-22 22:26:26 -04:00
}
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx := auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
got , err := s . AddTargetCredentialSources ( ctx , req )
2021-06-22 22:26:26 -04:00
require . NoError ( t , err , "Got error: %v" , s )
2022-07-19 15:16:24 -07:00
assert . ElementsMatch ( t , tc . resultSourceIds , got . GetItem (). GetBrokeredCredentialSourceIds ())
assert . Equal ( t , len ( tc . resultSourceIds ), len ( got . GetItem (). GetBrokeredCredentialSources ()))
2021-06-22 22:26:26 -04:00
})
}
2021-11-04 11:44:22 -04:00
tar := tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "test" )
2021-06-22 22:26:26 -04:00
failCases := [] struct {
name string
2021-07-27 12:48:36 -04:00
req * pbs . AddTargetCredentialSourcesRequest
2021-06-22 22:26:26 -04:00
err error
}{
{
2021-06-25 14:06:31 -04:00
name : "Bad target id" ,
2021-07-27 12:48:36 -04:00
req : & pbs . AddTargetCredentialSourcesRequest {
2024-02-13 09:17:41 -08:00
Id : "bad id" ,
2021-06-25 14:06:31 -04:00
Version : tar . GetVersion (),
2022-07-19 15:16:24 -07:00
BrokeredCredentialSourceIds : [] string {
2021-06-25 14:06:31 -04:00
cls [ 0 ]. GetPublicId (),
},
2021-06-22 22:26:26 -04:00
},
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
name : "Bad version" ,
2021-07-27 12:48:36 -04:00
req : & pbs . AddTargetCredentialSourcesRequest {
2021-06-25 14:06:31 -04:00
Id : tar . GetPublicId (),
Version : tar . GetVersion () + 2 ,
2022-07-19 15:16:24 -07:00
BrokeredCredentialSourceIds : [] string {
2021-06-25 14:06:31 -04:00
cls [ 0 ]. GetPublicId (),
},
2021-06-22 22:26:26 -04:00
},
err : handlers . ApiErrorWithCode ( codes . Internal ),
},
{
2021-07-27 12:48:36 -04:00
name : "Empty source list" ,
req : & pbs . AddTargetCredentialSourcesRequest {
2021-06-22 22:26:26 -04:00
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
},
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
2021-07-27 12:48:36 -04:00
name : "Incorrect source id" ,
req : & pbs . AddTargetCredentialSourcesRequest {
2022-07-19 15:16:24 -07:00
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
BrokeredCredentialSourceIds : [] string { "incorrect" },
2021-06-22 22:26:26 -04:00
},
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 )
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx := auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
_ , gErr := s . AddTargetCredentialSources ( ctx , tc . req )
2021-06-22 22:26:26 -04:00
if tc . err != nil {
require . Error ( gErr )
2021-07-27 12:48:36 -04:00
assert . True ( errors . Is ( gErr , tc . err ), "AddTargetCredentialSources(%+v) got error %v, wanted %v" , tc . req , gErr , tc . err )
2021-06-22 22:26:26 -04:00
}
})
}
}
2021-07-27 12:48:36 -04:00
func TestSetTargetCredentialSources ( t * testing . T ) {
2023-08-28 15:08:20 -07:00
t . Parallel ()
2023-06-06 17:09:08 -04:00
ctx := context . Background ()
2021-06-22 22:26:26 -04:00
conn , _ := db . TestSetup ( t , "postgres" )
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
2022-07-29 17:24:39 +00:00
rw := db . New ( conn )
2021-06-22 22:26:26 -04:00
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
2022-07-29 17:24:39 +00:00
tokenRepoFn := func () ( * authtoken . Repository , error ) {
2023-06-06 17:09:08 -04:00
return authtoken . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
2021-06-22 22:26:26 -04:00
2022-07-29 17:24:39 +00:00
org , proj := iam . TestScopes ( t , iamRepo )
at := authtoken . TestAuthToken ( t , conn , kms , org . GetPublicId ())
r := iam . TestRole ( t , conn , proj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2021-06-22 22:26:26 -04:00
2023-06-06 17:09:08 -04:00
s , err := testService ( t , ctx , conn , kms , wrapper )
2021-06-22 22:26:26 -04:00
require . NoError ( t , err , "Error when getting new target service." )
2022-06-08 13:51:56 -07:00
storeVault := vault . TestCredentialStores ( t , conn , wrapper , proj . GetPublicId (), 1 )[ 0 ]
cls := vault . TestCredentialLibraries ( t , conn , wrapper , storeVault . GetPublicId (), 2 )
2021-06-22 22:26:26 -04:00
2022-06-08 13:51:56 -07:00
storeStatic := credstatic . TestCredentialStore ( t , conn , wrapper , proj . GetPublicId ())
creds := credstatic . TestUsernamePasswordCredentials ( t , conn , wrapper , "user" , "pass" , storeStatic . GetPublicId (), proj . GetPublicId (), 2 )
2021-06-22 22:26:26 -04:00
setCases := [] struct {
2021-07-27 12:48:36 -04:00
name string
2024-02-13 09:17:41 -08:00
tar target . Target
2021-07-27 12:48:36 -04:00
setCredentialSources [] string
resultCredentialSourceIds [] string
2021-06-22 22:26:26 -04:00
}{
{
2022-06-09 15:35:55 -07:00
name : "Set library on empty target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "empty library" ),
2022-06-08 13:51:56 -07:00
setCredentialSources : [] string { cls [ 1 ]. GetPublicId ()},
resultCredentialSourceIds : [] string { cls [ 1 ]. GetPublicId ()},
},
{
name : "Set static on empty target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "empty static" ),
2022-06-08 13:51:56 -07:00
setCredentialSources : [] string { creds [ 1 ]. GetPublicId ()},
resultCredentialSourceIds : [] string { creds [ 1 ]. GetPublicId ()},
},
{
name : "Set library on library populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "populated library-library" , target . WithCredentialLibraries ([] * target . CredentialLibrary { target . TestNewCredentialLibrary ( "" , cls [ 0 ]. GetPublicId (), credential . BrokeredPurpose )})),
2021-07-27 12:48:36 -04:00
setCredentialSources : [] string { cls [ 1 ]. GetPublicId ()},
resultCredentialSourceIds : [] string { cls [ 1 ]. GetPublicId ()},
2022-06-08 13:51:56 -07:00
},
{
name : "Set static on library populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "populated static-library" , target . WithCredentialLibraries ([] * target . CredentialLibrary { target . TestNewCredentialLibrary ( "" , cls [ 0 ]. GetPublicId (), credential . BrokeredPurpose )})),
2022-06-08 13:51:56 -07:00
setCredentialSources : [] string { creds [ 1 ]. GetPublicId ()},
resultCredentialSourceIds : [] string { creds [ 1 ]. GetPublicId ()},
2021-07-27 12:48:36 -04:00
},
{
2022-06-08 13:51:56 -07:00
name : "Set library on static populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "populated library-static" , target . WithStaticCredentials ([] * target . StaticCredential { target . TestNewStaticCredential ( "" , creds [ 0 ]. GetPublicId (), credential . BrokeredPurpose )})),
2021-07-27 12:48:36 -04:00
setCredentialSources : [] string { cls [ 1 ]. GetPublicId ()},
resultCredentialSourceIds : [] string { cls [ 1 ]. GetPublicId ()},
},
{
2022-06-08 13:51:56 -07:00
name : "Set static on static populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "populated static-static" , target . WithStaticCredentials ([] * target . StaticCredential { target . TestNewStaticCredential ( "" , creds [ 0 ]. GetPublicId (), credential . BrokeredPurpose )})),
2022-06-08 13:51:56 -07:00
setCredentialSources : [] string { creds [ 1 ]. GetPublicId ()},
resultCredentialSourceIds : [] string { creds [ 1 ]. GetPublicId ()},
2021-06-22 22:26:26 -04:00
},
{
2022-06-08 13:51:56 -07:00
name : "Set duplicate library on populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "duplicate library" , target . WithCredentialLibraries ([] * target . CredentialLibrary { target . TestNewCredentialLibrary ( "" , cls [ 0 ]. GetPublicId (), credential . BrokeredPurpose )})),
2021-07-27 12:48:36 -04:00
setCredentialSources : [] string { cls [ 1 ]. GetPublicId (), cls [ 1 ]. GetPublicId ()},
resultCredentialSourceIds : [] string { cls [ 1 ]. GetPublicId ()},
2021-06-22 22:26:26 -04:00
},
{
2022-06-08 13:51:56 -07:00
name : "Set duplicate static on populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "duplicate static" , target . WithStaticCredentials ([] * target . StaticCredential { target . TestNewStaticCredential ( "" , creds [ 0 ]. GetPublicId (), credential . BrokeredPurpose )})),
2022-06-08 13:51:56 -07:00
setCredentialSources : [] string { creds [ 1 ]. GetPublicId (), creds [ 1 ]. GetPublicId ()},
resultCredentialSourceIds : [] string { creds [ 1 ]. GetPublicId ()},
2021-06-22 22:26:26 -04:00
},
{
2022-06-08 13:51:56 -07:00
name : "Set empty on populated target" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "another populated" ,
2022-07-19 15:16:24 -07:00
target . WithCredentialLibraries ([] * target . CredentialLibrary { target . TestNewCredentialLibrary ( "" , cls [ 0 ]. GetPublicId (), credential . BrokeredPurpose )}),
2024-02-13 09:17:41 -08:00
target . WithStaticCredentials ([] * target . StaticCredential { target . TestNewStaticCredential ( "" , creds [ 0 ]. GetPublicId (), credential . BrokeredPurpose )})),
2021-07-27 12:48:36 -04:00
setCredentialSources : [] string {},
resultCredentialSourceIds : nil ,
2021-06-22 22:26:26 -04:00
},
}
for _ , tc := range setCases {
t . Run ( tc . name , func ( t * testing . T ) {
2021-07-27 12:48:36 -04:00
req := & pbs . SetTargetCredentialSourcesRequest {
2024-02-13 09:17:41 -08:00
Id : tc . tar . GetPublicId (),
Version : tc . tar . GetVersion (),
2022-07-19 15:16:24 -07:00
BrokeredCredentialSourceIds : tc . setCredentialSources ,
2021-06-22 22:26:26 -04:00
}
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
2023-06-06 17:09:08 -04:00
requestContext := context . WithValue ( ctx , requests . ContextRequestInformationKey , & requests . RequestContext {})
2022-07-29 17:24:39 +00:00
ctx := auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
got , err := s . SetTargetCredentialSources ( ctx , req )
2021-06-22 22:26:26 -04:00
require . NoError ( t , err , "Got error: %v" , s )
2022-07-19 15:16:24 -07:00
assert . ElementsMatch ( t , tc . resultCredentialSourceIds , got . GetItem (). GetBrokeredCredentialSourceIds ())
assert . Equal ( t , len ( tc . resultCredentialSourceIds ), len ( got . GetItem (). GetBrokeredCredentialSources ()))
2021-06-22 22:26:26 -04:00
})
}
2021-11-04 11:44:22 -04:00
tar := tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "test name" )
2021-06-22 22:26:26 -04:00
failCases := [] struct {
name string
2021-07-27 12:48:36 -04:00
req * pbs . SetTargetCredentialSourcesRequest
2021-06-22 22:26:26 -04:00
err error
}{
{
name : "Bad target Id" ,
2021-07-27 12:48:36 -04:00
req : & pbs . SetTargetCredentialSourcesRequest {
2024-02-13 09:17:41 -08:00
Id : "bad id" ,
2022-07-19 15:16:24 -07:00
Version : tar . GetVersion (),
BrokeredCredentialSourceIds : [] string { cls [ 0 ]. GetPublicId ()},
2021-06-22 22:26:26 -04:00
},
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
name : "Bad version" ,
2021-07-27 12:48:36 -04:00
req : & pbs . SetTargetCredentialSourcesRequest {
2022-07-19 15:16:24 -07:00
Id : tar . GetPublicId (),
Version : tar . GetVersion () + 3 ,
BrokeredCredentialSourceIds : [] string { cls [ 0 ]. GetPublicId ()},
2021-06-22 22:26:26 -04:00
},
err : handlers . ApiErrorWithCode ( codes . Internal ),
},
{
2021-07-27 12:48:36 -04:00
name : "Bad source id" ,
req : & pbs . SetTargetCredentialSourcesRequest {
2022-07-19 15:16:24 -07:00
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
BrokeredCredentialSourceIds : [] string { "invalid" },
2021-06-22 22:26:26 -04:00
},
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 )
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx := auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
_ , gErr := s . SetTargetCredentialSources ( ctx , tc . req )
2021-06-22 22:26:26 -04:00
if tc . err != nil {
require . Error ( gErr )
2021-07-27 12:48:36 -04:00
assert . True ( errors . Is ( gErr , tc . err ), "SetTargetCredentialSources(%+v) got error %v, wanted %v" , tc . req , gErr , tc . err )
2021-06-22 22:26:26 -04:00
}
})
}
}
2021-07-27 12:48:36 -04:00
func TestRemoveTargetCredentialSources ( t * testing . T ) {
2023-08-28 15:08:20 -07:00
t . Parallel ()
2023-06-06 17:09:08 -04:00
ctx := context . Background ()
2021-06-22 22:26:26 -04:00
conn , _ := db . TestSetup ( t , "postgres" )
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
2022-07-29 17:24:39 +00:00
rw := db . New ( conn )
2021-06-22 22:26:26 -04:00
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
2022-07-29 17:24:39 +00:00
tokenRepoFn := func () ( * authtoken . Repository , error ) {
2023-06-06 17:09:08 -04:00
return authtoken . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2022-07-29 17:24:39 +00:00
}
2021-06-22 22:26:26 -04:00
2022-07-29 17:24:39 +00:00
org , proj := iam . TestScopes ( t , iamRepo )
at := authtoken . TestAuthToken ( t , conn , kms , org . GetPublicId ())
r := iam . TestRole ( t , conn , proj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2021-06-22 22:26:26 -04:00
2023-06-06 17:09:08 -04:00
s , err := testService ( t , ctx , conn , kms , wrapper )
2021-06-22 22:26:26 -04:00
require . NoError ( t , err , "Error when getting new target service." )
2022-06-08 13:51:56 -07:00
csVault := vault . TestCredentialStores ( t , conn , wrapper , proj . GetPublicId (), 1 )[ 0 ]
cls := vault . TestCredentialLibraries ( t , conn , wrapper , csVault . GetPublicId (), 2 )
csStatic := credstatic . TestCredentialStores ( t , conn , wrapper , proj . GetPublicId (), 1 )[ 0 ]
creds := credstatic . TestUsernamePasswordCredentials ( t , conn , wrapper , "u" , "p" , csStatic . GetPublicId (), proj . GetPublicId (), 2 )
2021-06-22 22:26:26 -04:00
removeCases := [] struct {
2021-07-27 12:48:36 -04:00
name string
2024-02-13 09:17:41 -08:00
tar target . Target
2021-07-27 12:48:36 -04:00
removeCredentialSources [] string
resultCredentialSourceIds [] string
wantErr bool
2021-06-22 22:26:26 -04:00
}{
{
2022-06-08 13:51:56 -07:00
name : "Remove library from empty" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "empty lib" ),
2021-07-27 12:48:36 -04:00
removeCredentialSources : [] string { cls [ 1 ]. GetPublicId ()},
wantErr : true ,
},
{
2022-06-08 13:51:56 -07:00
name : "Remove static from empty" ,
2024-02-13 09:17:41 -08:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "empty static" ),
2022-06-08 13:51:56 -07:00
removeCredentialSources : [] string { creds [ 1 ]. GetPublicId ()},
wantErr : true ,
},
{
name : "Remove 1 of 2 libraries" ,
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "remove partial lib" ,
target . WithCredentialLibraries ([] * target . CredentialLibrary {
2022-07-19 15:16:24 -07:00
target . TestNewCredentialLibrary ( "" , cls [ 0 ]. GetPublicId (), credential . BrokeredPurpose ),
target . TestNewCredentialLibrary ( "" , cls [ 1 ]. GetPublicId (), credential . BrokeredPurpose ),
2024-02-13 09:17:41 -08:00
})),
2021-07-27 12:48:36 -04:00
removeCredentialSources : [] string { cls [ 1 ]. GetPublicId ()},
resultCredentialSourceIds : [] string { cls [ 0 ]. GetPublicId ()},
2021-06-22 22:26:26 -04:00
},
{
2022-06-08 13:51:56 -07:00
name : "Remove 1 of 2 static credentials" ,
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "remove partial static" ,
target . WithStaticCredentials ([] * target . StaticCredential {
2022-07-19 15:16:24 -07:00
target . TestNewStaticCredential ( "" , creds [ 0 ]. GetPublicId (), credential . BrokeredPurpose ),
target . TestNewStaticCredential ( "" , creds [ 1 ]. GetPublicId (), credential . BrokeredPurpose ),
2024-02-13 09:17:41 -08:00
})),
2022-06-08 13:51:56 -07:00
removeCredentialSources : [] string { creds [ 1 ]. GetPublicId ()},
resultCredentialSourceIds : [] string { creds [ 0 ]. GetPublicId ()},
2021-06-22 22:26:26 -04:00
},
{
2021-06-25 14:06:31 -04:00
name : "Remove 1 duplicate set of 2 libraries" ,
2022-06-08 13:51:56 -07:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "remove duplicate lib" ,
target . WithCredentialLibraries ([] * target . CredentialLibrary {
2022-07-19 15:16:24 -07:00
target . TestNewCredentialLibrary ( "" , cls [ 0 ]. GetPublicId (), credential . BrokeredPurpose ),
target . TestNewCredentialLibrary ( "" , cls [ 1 ]. GetPublicId (), credential . BrokeredPurpose ),
2024-02-13 09:17:41 -08:00
})),
2021-07-27 12:48:36 -04:00
removeCredentialSources : [] string {
2021-06-25 14:06:31 -04:00
cls [ 1 ]. GetPublicId (), cls [ 1 ]. GetPublicId (),
},
2021-07-27 12:48:36 -04:00
resultCredentialSourceIds : [] string { cls [ 0 ]. GetPublicId ()},
2022-06-08 13:51:56 -07:00
},
{
name : "Remove 1 duplicate set of 2 static credentials" ,
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "remove duplicate static" ,
target . WithStaticCredentials ([] * target . StaticCredential {
2022-07-19 15:16:24 -07:00
target . TestNewStaticCredential ( "" , creds [ 0 ]. GetPublicId (), credential . BrokeredPurpose ),
target . TestNewStaticCredential ( "" , creds [ 1 ]. GetPublicId (), credential . BrokeredPurpose ),
2024-02-13 09:17:41 -08:00
})),
2022-06-08 13:51:56 -07:00
removeCredentialSources : [] string {
creds [ 1 ]. GetPublicId (), creds [ 1 ]. GetPublicId (),
},
resultCredentialSourceIds : [] string { creds [ 0 ]. GetPublicId ()},
},
{
name : "Remove mixed sources from target" ,
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "remove mixed" ,
target . WithCredentialLibraries ([] * target . CredentialLibrary {
2022-07-19 15:16:24 -07:00
target . TestNewCredentialLibrary ( "" , cls [ 0 ]. GetPublicId (), credential . BrokeredPurpose ),
target . TestNewCredentialLibrary ( "" , cls [ 1 ]. GetPublicId (), credential . BrokeredPurpose ),
2022-06-08 13:51:56 -07:00
}),
target . WithStaticCredentials ([] * target . StaticCredential {
2022-07-19 15:16:24 -07:00
target . TestNewStaticCredential ( "" , creds [ 0 ]. GetPublicId (), credential . BrokeredPurpose ),
target . TestNewStaticCredential ( "" , creds [ 1 ]. GetPublicId (), credential . BrokeredPurpose ),
2024-02-13 09:17:41 -08:00
})),
2022-06-08 13:51:56 -07:00
removeCredentialSources : [] string {
cls [ 1 ]. GetPublicId (), creds [ 0 ]. GetPublicId (),
},
resultCredentialSourceIds : [] string {
cls [ 0 ]. GetPublicId (), creds [ 1 ]. GetPublicId (),
},
2021-06-22 22:26:26 -04:00
},
{
2021-07-27 12:48:36 -04:00
name : "Remove all sources from target" ,
2022-06-08 13:51:56 -07:00
tar : tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "remove all" ,
target . WithCredentialLibraries ([] * target . CredentialLibrary {
2022-07-19 15:16:24 -07:00
target . TestNewCredentialLibrary ( "" , cls [ 0 ]. GetPublicId (), credential . BrokeredPurpose ),
target . TestNewCredentialLibrary ( "" , cls [ 1 ]. GetPublicId (), credential . BrokeredPurpose ),
2022-06-08 13:51:56 -07:00
}),
target . WithStaticCredentials ([] * target . StaticCredential {
2022-07-19 15:16:24 -07:00
target . TestNewStaticCredential ( "" , creds [ 0 ]. GetPublicId (), credential . BrokeredPurpose ),
target . TestNewStaticCredential ( "" , creds [ 1 ]. GetPublicId (), credential . BrokeredPurpose ),
2024-02-13 09:17:41 -08:00
})),
2021-07-27 12:48:36 -04:00
removeCredentialSources : [] string {
2021-06-25 14:06:31 -04:00
cls [ 0 ]. GetPublicId (), cls [ 1 ]. GetPublicId (),
2022-06-08 13:51:56 -07:00
creds [ 0 ]. GetPublicId (), creds [ 1 ]. GetPublicId (),
2021-06-25 14:06:31 -04:00
},
2021-07-27 12:48:36 -04:00
resultCredentialSourceIds : [] string {},
2021-06-22 22:26:26 -04:00
},
}
for _ , tc := range removeCases {
t . Run ( tc . name , func ( t * testing . T ) {
2021-07-27 12:48:36 -04:00
req := & pbs . RemoveTargetCredentialSourcesRequest {
2024-02-13 09:17:41 -08:00
Id : tc . tar . GetPublicId (),
Version : tc . tar . GetVersion (),
2022-07-19 15:16:24 -07:00
BrokeredCredentialSourceIds : tc . removeCredentialSources ,
2021-06-22 22:26:26 -04:00
}
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx := auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
got , err := s . RemoveTargetCredentialSources ( ctx , req )
2021-06-22 22:26:26 -04:00
if tc . wantErr {
assert . Error ( t , err )
return
}
require . NoError ( t , err , "Got error: %v" , s )
2022-07-19 15:16:24 -07:00
assert . ElementsMatch ( t , tc . resultCredentialSourceIds , got . GetItem (). GetBrokeredCredentialSourceIds ())
assert . Equal ( t , len ( tc . resultCredentialSourceIds ), len ( got . GetItem (). GetBrokeredCredentialSources ()))
2021-06-22 22:26:26 -04:00
})
}
2021-11-04 11:44:22 -04:00
tar := tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), "testing" )
2021-06-22 22:26:26 -04:00
failCases := [] struct {
name string
2021-07-27 12:48:36 -04:00
req * pbs . RemoveTargetCredentialSourcesRequest
2021-06-22 22:26:26 -04:00
err error
}{
{
name : "Bad version" ,
2021-07-27 12:48:36 -04:00
req : & pbs . RemoveTargetCredentialSourcesRequest {
2021-06-25 14:06:31 -04:00
Id : tar . GetPublicId (),
Version : tar . GetVersion () + 3 ,
2022-07-19 15:16:24 -07:00
BrokeredCredentialSourceIds : [] string {
2021-06-25 14:06:31 -04:00
cls [ 0 ]. GetPublicId (),
},
2021-06-22 22:26:26 -04:00
},
err : handlers . ApiErrorWithCode ( codes . Internal ),
},
{
name : "Bad target Id" ,
2021-07-27 12:48:36 -04:00
req : & pbs . RemoveTargetCredentialSourcesRequest {
2024-02-13 09:17:41 -08:00
Id : "bad id" ,
2021-06-25 14:06:31 -04:00
Version : tar . GetVersion (),
2022-07-19 15:16:24 -07:00
BrokeredCredentialSourceIds : [] string {
2021-06-25 14:06:31 -04:00
cls [ 0 ]. GetPublicId (),
},
2021-06-22 22:26:26 -04:00
},
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
2021-07-27 12:48:36 -04:00
name : "Empty sources" ,
req : & pbs . RemoveTargetCredentialSourcesRequest {
2022-07-19 15:16:24 -07:00
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
BrokeredCredentialSourceIds : [] string {},
2021-06-22 22:26:26 -04:00
},
err : handlers . ApiErrorWithCode ( codes . InvalidArgument ),
},
{
2021-07-27 12:48:36 -04:00
name : "Invalid source ids" ,
req : & pbs . RemoveTargetCredentialSourcesRequest {
2021-06-25 14:06:31 -04:00
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
2022-07-19 15:16:24 -07:00
BrokeredCredentialSourceIds : [] string {
2021-06-25 14:06:31 -04:00
"invalid" ,
},
2021-06-22 22:26:26 -04:00
},
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 )
2022-07-29 17:24:39 +00:00
requestInfo := authpb . RequestInfo {
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
Token : at . GetToken (),
}
requestContext := context . WithValue ( context . Background (), requests . ContextRequestInformationKey , & requests . RequestContext {})
ctx := auth . NewVerifierContext ( requestContext , iamRepoFn , tokenRepoFn , serversRepoFn , kms , & requestInfo )
_ , gErr := s . RemoveTargetCredentialSources ( ctx , tc . req )
2021-06-22 22:26:26 -04:00
if tc . err != nil {
require . Error ( gErr )
2021-07-27 12:48:36 -04:00
assert . True ( errors . Is ( gErr , tc . err ), "RemoveTargetCredentialSources(%+v) got error %v, wanted %v" , tc . req , gErr , tc . err )
2021-06-22 22:26:26 -04:00
}
})
}
}
func TestAuthorizeSession ( t * testing . T ) {
2021-11-01 09:07:56 -07:00
ctx := context . Background ()
2023-09-07 11:52:00 -07:00
// This prevents us from running tests in parallel.
2025-01-08 15:18:03 +00:00
server . TestUseCommunityFilterWorkersFn ( t )
2021-07-27 12:48:36 -04:00
conn , _ := db . TestSetup ( t , "postgres" )
2021-06-22 22:26:26 -04:00
rw := db . New ( conn )
2021-07-27 12:48:36 -04:00
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
2021-06-22 22:26:26 -04:00
sche := scheduler . TestScheduler ( t , conn , wrapper )
2021-10-22 15:53:18 -07:00
err := vault . RegisterJobs ( context . Background (), sche , rw , rw , kms )
require . NoError ( t , err )
2022-08-23 17:27:56 +01:00
repoFn := func ( o ... target . Option ) ( * target . Repository , error ) {
2022-08-23 18:44:10 +01:00
return target . NewRepository ( ctx , rw , rw , kms )
2021-06-22 22:26:26 -04:00
}
2021-07-27 12:48:36 -04:00
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
2022-06-20 18:20:17 -07:00
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2021-06-22 22:26:26 -04:00
}
2022-08-09 12:43:38 +00:00
sessionRepoFn := func ( opts ... session . Option ) ( * session . Repository , error ) {
2022-08-24 13:22:03 +00:00
return session . NewRepository ( ctx , rw , rw , kms , opts ... )
2021-06-22 22:26:26 -04:00
}
2023-06-06 17:09:08 -04:00
staticRepo , err := static . NewRepository ( ctx , rw , rw , kms )
2022-06-13 08:26:24 -07:00
require . NoError ( t , err )
2021-06-22 22:26:26 -04:00
staticHostRepoFn := func () ( * static . Repository , error ) {
2022-06-13 08:26:24 -07:00
return staticRepo , nil
2021-06-22 22:26:26 -04:00
}
2022-06-09 15:35:55 -07:00
vaultCredRepoFn := func () ( * vault . Repository , error ) {
2023-06-06 17:09:08 -04:00
return vault . NewRepository ( ctx , rw , rw , kms , sche )
2021-06-22 22:26:26 -04:00
}
2022-06-09 15:35:55 -07:00
staticCredRepoFn := func () ( * credstatic . Repository , error ) {
return credstatic . NewRepository ( ctx , rw , rw , kms )
}
2021-06-22 22:26:26 -04:00
atRepoFn := func () ( * authtoken . Repository , error ) {
2023-06-06 17:09:08 -04:00
return authtoken . NewRepository ( ctx , rw , rw , kms )
2021-06-22 22:26:26 -04:00
}
2022-10-27 09:01:05 -04:00
passwordAuthRepoFn := func () ( * password . Repository , error ) {
2023-06-06 17:09:08 -04:00
return password . NewRepository ( ctx , rw , rw , kms )
2022-10-27 09:01:05 -04:00
}
oidcAuthRepoFn := func () ( * oidc . Repository , error ) {
return oidc . NewRepository ( ctx , rw , rw , kms )
}
2023-03-15 11:40:40 -04:00
ldapAuthRepoFn := func () ( * ldap . Repository , error ) {
return ldap . NewRepository ( ctx , rw , rw , kms )
}
2024-02-01 08:58:56 -08:00
targetAliasRepoFn := func () ( * talias . Repository , error ) {
return talias . NewRepository ( ctx , rw , rw , kms )
}
2021-07-27 12:48:36 -04:00
2023-04-24 19:27:41 -04:00
plg := plugin . TestPlugin ( t , conn , "test" )
2021-10-07 11:56:39 -04:00
plgm := map [ string ] plgpb . HostPluginServiceClient {
2023-04-18 21:12:05 -07:00
plg . GetPublicId (): loopback . NewWrappingPluginHostClient ( loopback . TestPluginHostServer {
2021-09-26 08:17:21 -07:00
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 {
{
2021-09-26 11:48:43 -04:00
SetIds : setIds ,
2021-09-26 08:17:21 -07:00
ExternalId : "test" ,
IpAddresses : [] string { "10.0.0.1" , "192.168.0.1" },
2022-02-10 16:06:03 -07:00
DnsNames : [] string { "example.com" },
2021-09-26 08:17:21 -07:00
},
{
2021-09-26 11:48:43 -04:00
SetIds : setIds ,
2021-09-26 08:17:21 -07:00
ExternalId : "test2" ,
IpAddresses : [] string { "10.1.1.1" , "192.168.1.1" },
2022-02-10 16:06:03 -07:00
DnsNames : [] string { "another-example.com" },
2021-09-26 08:17:21 -07:00
},
}}, nil
},
2021-10-07 11:56:39 -04:00
}),
2021-09-26 08:17:21 -07:00
}
2023-04-24 19:27:41 -04:00
pluginHostRepoFn := func () ( * hostplugin . Repository , error ) {
2023-06-06 17:09:08 -04:00
return hostplugin . NewRepository ( ctx , rw , rw , kms , sche , plgm )
2021-09-26 08:17:21 -07:00
}
2021-07-27 12:48:36 -04:00
2022-10-27 09:01:05 -04:00
loginName := "foo@bar.com"
accountName := "passname"
userName := "username"
2021-06-22 22:26:26 -04:00
org , proj := iam . TestScopes ( t , iamRepo )
2022-10-27 09:01:05 -04:00
at := authtoken . TestAuthToken ( t ,
conn ,
kms ,
org . GetPublicId (),
authtoken . WithPasswordOptions ( password . WithLoginName ( loginName ), password . WithName ( accountName )),
authtoken . WithIamOptions ( iam . WithName ( userName )))
ctx = auth . NewVerifierContextWithAccounts ( requests . NewRequestContext ( ctx ),
2021-06-22 22:26:26 -04:00
iamRepoFn ,
atRepoFn ,
serversRepoFn ,
2022-10-27 09:01:05 -04:00
passwordAuthRepoFn ,
oidcAuthRepoFn ,
2023-03-15 11:40:40 -04:00
ldapAuthRepoFn ,
2021-06-22 22:26:26 -04:00
kms ,
2021-10-19 17:21:41 -04:00
& authpb . RequestInfo {
2021-06-22 22:26:26 -04:00
Token : at . GetToken (),
2021-10-19 17:21:41 -04:00
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
2021-06-22 22:26:26 -04:00
PublicId : at . GetPublicId (),
})
2021-07-27 12:48:36 -04:00
2021-06-22 22:26:26 -04:00
r := iam . TestRole ( t , conn , proj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2021-06-22 22:26:26 -04:00
hc := static . TestCatalogs ( t , conn , proj . GetPublicId (), 1 )[ 0 ]
h := static . TestHosts ( t , conn , hc . GetPublicId (), 1 )[ 0 ]
2021-09-26 08:17:21 -07:00
shs := static . TestSets ( t , conn , hc . GetPublicId (), 1 )[ 0 ]
_ = static . TestSetMembers ( t , conn , shs . GetPublicId (), [] * static . Host { h })
2021-06-22 22:26:26 -04:00
2022-06-13 08:26:24 -07:00
hcWithPort := static . TestCatalogs ( t , conn , proj . GetPublicId (), 1 )[ 0 ]
hWithPort := static . TestHosts ( t , conn , hcWithPort . GetPublicId (), 1 )[ 0 ]
shsWithPort := static . TestSets ( t , conn , hcWithPort . GetPublicId (), 1 )[ 0 ]
_ = static . TestSetMembers ( t , conn , shsWithPort . GetPublicId (), [] * static . Host { hWithPort })
2023-01-26 10:35:29 -08:00
hWithPortBareAddress := hWithPort . GetAddress ()
2022-07-20 16:24:46 -07:00
hWithPort , _ , err = staticRepo . UpdateHost ( ctx , hcWithPort . GetProjectId (), hWithPort , hWithPort . GetVersion (), [] string { "address" })
2022-06-13 08:26:24 -07:00
require . NoError ( t , err )
2023-04-24 19:27:41 -04:00
phc := hostplugin . TestCatalog ( t , conn , proj . GetPublicId (), plg . GetPublicId ())
phs := hostplugin . TestSet ( t , conn , kms , sche , phc , plgm , hostplugin . WithPreferredEndpoints ([] string { "cidr:10.0.0.0/24" }))
2021-11-01 09:07:56 -07:00
// Sync the boundary db from the plugins
2023-04-24 19:27:41 -04:00
hostplugin . TestRunSetSync ( t , conn , kms , plgm )
2021-06-22 22:26:26 -04:00
v := vault . NewTestVaultServer ( t )
2022-10-27 09:01:05 -04:00
v . MountPKI ( t , vault . WithTestMountPath ( "pki/" + userName ))
2021-06-22 22:26:26 -04:00
sec , tok := v . CreateToken ( t , vault . WithPolicies ([] string { "default" , "boundary-controller" , "pki" }))
2022-06-09 15:35:55 -07:00
vaultStore := vault . TestCredentialStore ( t , conn , wrapper , proj . GetPublicId (), v . Addr , tok , sec . Auth . Accessor )
2023-12-01 16:16:19 -08:00
credService , err := credentiallibraries . NewService ( ctx , iamRepoFn , vaultCredRepoFn , 1000 )
2021-06-22 22:26:26 -04:00
require . NoError ( t , err )
2022-06-09 15:35:55 -07:00
clsResp , err := credService . CreateCredentialLibrary ( ctx , & pbs . CreateCredentialLibraryRequest { Item : & credlibpb . CredentialLibrary {
CredentialStoreId : vaultStore . GetPublicId (),
2021-06-22 22:26:26 -04:00
Name : wrapperspb . String ( "Library Name" ),
Description : wrapperspb . String ( "Library Description" ),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2022-06-09 15:35:55 -07:00
Attrs : & credlibpb . CredentialLibrary_VaultCredentialLibraryAttributes {
VaultCredentialLibraryAttributes : & credlibpb . VaultCredentialLibraryAttributes {
2022-04-06 15:29:00 -04:00
Path : & wrapperspb . StringValue {
2022-10-27 09:01:05 -04:00
Value : path . Join ( "pki/{{ .User.Name}}" , "issue" , "boundary" ),
2022-04-06 15:29:00 -04:00
},
HttpMethod : & wrapperspb . StringValue {
Value : "POST" ,
},
HttpRequestBody : & wrapperspb . StringValue {
2022-10-27 09:01:05 -04:00
Value : `{"common_name":"boundary.com", "alt_names": " {{ .User.Name }} , {{ .Account.Name }} , {{ .Account.LoginName }} , {{ truncateFrom .Account.LoginName "@" }} "}` ,
2022-04-06 15:29:00 -04:00
},
},
},
2021-06-22 22:26:26 -04:00
}})
require . NoError ( t , err )
2022-06-13 08:26:24 -07:00
const defaultPort = 2
2021-09-26 08:17:21 -07:00
cases := [] struct {
2024-12-30 14:16:39 -05:00
name string
hostSourceId string
credSourceId string
wantedHostId string
wantedEndpoint string
wantedConnectionLimit int32
2021-09-26 08:17:21 -07:00
}{
{
2024-12-30 14:16:39 -05:00
name : "static host" ,
hostSourceId : shs . GetPublicId (),
credSourceId : clsResp . GetItem (). GetId (),
wantedHostId : h . GetPublicId (),
wantedEndpoint : fmt . Sprintf ( "%s:%d" , h . GetAddress (), defaultPort ),
wantedConnectionLimit : - 1 ,
2022-06-13 08:26:24 -07:00
},
{
2024-12-30 14:16:39 -05:00
name : "static host with port defined" ,
hostSourceId : shsWithPort . GetPublicId (),
credSourceId : clsResp . GetItem (). GetId (),
wantedHostId : hWithPort . GetPublicId (),
wantedEndpoint : fmt . Sprintf ( "%s:%d" , hWithPortBareAddress , defaultPort ),
wantedConnectionLimit : 10 ,
2021-09-26 08:17:21 -07:00
},
{
2024-12-30 14:16:39 -05:00
name : "plugin host" ,
hostSourceId : phs . GetPublicId (),
credSourceId : clsResp . GetItem (). GetId (),
wantedHostId : "?" ,
wantedEndpoint : fmt . Sprintf ( "10.0.0.1:%d" , defaultPort ),
wantedConnectionLimit : 100 ,
2021-06-24 09:39:41 -04:00
},
2021-06-22 22:26:26 -04:00
}
2025-01-09 10:26:37 -08:00
workerRPCGracePeriod := new ( atomic . Int64 )
workerRPCGracePeriod . Store ( int64 ( server . DefaultLiveness ))
s , err := targets . NewService ( ctx , kms , repoFn , iamRepoFn , serversRepoFn , sessionRepoFn , pluginHostRepoFn , staticHostRepoFn , vaultCredRepoFn , staticCredRepoFn , targetAliasRepoFn , nil , workerRPCGracePeriod , 1000 , nil )
2022-06-13 08:26:24 -07:00
require . NoError ( t , err )
2021-09-26 08:17:21 -07:00
for _ , tc := range cases {
t . Run ( tc . name , func ( t * testing . T ) {
2024-04-06 13:48:47 -07:00
// Generate correlation Id and add it to the context
corId , err := uuid . GenerateUUID ()
require . NoError ( t , err )
ctx , err = event . NewCorrelationIdContext ( ctx , corId )
require . NoError ( t , err )
2024-12-30 14:16:39 -05:00
tar := tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), tc . name , target . WithDefaultPort ( defaultPort ), target . WithSessionConnectionLimit ( tc . wantedConnectionLimit ))
2022-06-15 08:56:24 -07:00
apiTar , err := s . AddTargetHostSources ( ctx , & pbs . AddTargetHostSourcesRequest {
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
HostSourceIds : [] string { tc . hostSourceId },
2021-09-26 08:17:21 -07:00
})
require . NoError ( t , err )
_ , err = s . AddTargetCredentialSources ( ctx ,
& pbs . AddTargetCredentialSourcesRequest {
2022-07-19 15:16:24 -07:00
Id : tar . GetPublicId (),
BrokeredCredentialSourceIds : [] string { clsResp . GetItem (). GetId ()},
Version : apiTar . GetItem (). GetVersion (),
2021-09-26 08:17:21 -07:00
})
require . NoError ( t , err )
// Tell our DB that there is a worker ready to serve the data
2022-06-20 18:20:17 -07:00
server . TestKmsWorker ( t , conn , wrapper )
2021-06-22 22:26:26 -04:00
2021-09-26 08:17:21 -07:00
asRes1 , err := s . AuthorizeSession ( ctx , & pbs . AuthorizeSessionRequest {
2024-02-13 09:17:41 -08:00
Id : tar . GetPublicId (),
2021-09-26 08:17:21 -07:00
})
require . NoError ( t , err )
asRes2 , err := s . AuthorizeSession ( ctx , & pbs . AuthorizeSessionRequest {
2024-02-13 09:17:41 -08:00
Id : tar . GetPublicId (),
2021-09-26 08:17:21 -07:00
})
require . NoError ( t , err )
2023-10-31 13:44:17 +00:00
assert . NotEmpty ( t , cmp . Diff (
asRes1 . GetItem (). GetCredentials (),
asRes2 . GetItem (). GetCredentials (),
protocmp . Transform (),
cmpopts . SortSlices ( func ( a , b string ) bool {
return a < b
}),
),
2021-09-26 08:17:21 -07:00
"the credentials aren't unique per request authorized session" )
2022-02-10 15:59:57 -05:00
_ , err = s . AuthorizeSession ( ctx , & pbs . AuthorizeSessionRequest {
2024-02-13 09:17:41 -08:00
Id : tar . GetPublicId (),
2022-02-10 15:59:57 -05:00
HostId : asRes2 . GetItem (). GetHostId (),
})
require . NoError ( t , err , "session must authorize with explicit host ID" )
2021-09-26 08:17:21 -07:00
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 ),
2023-10-22 17:48:54 -07:00
Credentials : [] * pb . SessionCredential {
{
CredentialSource : & pb . CredentialSource {
Id : clsResp . GetItem (). GetId (),
Name : clsResp . GetItem (). GetName (). GetValue (),
Description : clsResp . GetItem (). GetDescription (). GetValue (),
CredentialStoreId : vaultStore . GetPublicId (),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2023-10-22 17:48:54 -07:00
},
2021-09-26 08:17:21 -07:00
},
2023-10-22 17:48:54 -07:00
},
2024-12-30 14:16:39 -05:00
EndpointPort : uint32 ( defaultPort ),
ConnectionLimit : tc . wantedConnectionLimit ,
2021-09-26 08:17:21 -07:00
// TODO: validate the contents of the authorization token is what is expected
}
2022-10-25 18:29:38 -05:00
wantSecret := map [ string ] any {
2021-09-26 08:17:21 -07:00
"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 )
}
2022-10-27 09:01:05 -04:00
b , _ := pem . Decode ([] byte ( dSec [ "certificate" ].( string )))
require . NotNil ( t , b )
cert , err := x509 . ParseCertificate ( b . Bytes )
require . NoError ( t , err )
assert . Contains ( t , cert . DNSNames , userName )
assert . Contains ( t , cert . DNSNames , accountName )
assert . Contains ( t , cert . DNSNames , strings . Split ( loginName , "@" )[ 0 ])
assert . Contains ( t , cert . EmailAddresses , loginName )
2021-09-26 08:17:21 -07:00
gotCred . Secret = nil
2021-06-22 22:26:26 -04:00
2024-04-06 13:48:47 -07:00
// CorrelationId is not part of the authSession resp, query the session directly
sessRepo , err := sessionRepoFn ()
require . NoError ( t , err )
gotSess , _ , err := sessRepo . LookupSession ( ctx , got . SessionId )
require . NoError ( t , err )
require . Equal ( t , corId , gotSess . CorrelationId )
2021-09-26 08:17:21 -07:00
got . AuthorizationToken , got . SessionId , got . CreatedTime = "" , "" , nil
2023-10-31 13:44:17 +00:00
assert . Empty ( t , cmp . Diff (
got ,
want ,
protocmp . Transform (),
protocmp . IgnoreFields ( & pb . SessionAuthorization {}, "expiration" ),
cmpopts . SortSlices ( func ( a , b string ) bool {
return a < b
}),
))
2022-01-05 14:15:38 -08:00
})
}
}
func TestAuthorizeSessionTypedCredentials ( t * testing . T ) {
ctx := context . Background ()
conn , _ := db . TestSetup ( t , "postgres" )
rw := db . New ( conn )
wrapper := db . TestWrapper ( t )
kms := kms . TestKms ( t , conn , wrapper )
2023-09-07 11:52:00 -07:00
// This prevents us from running tests in parallel.
2025-01-08 15:18:03 +00:00
server . TestUseCommunityFilterWorkersFn ( t )
2023-01-05 12:09:31 -05:00
2022-01-05 14:15:38 -08:00
sche := scheduler . TestScheduler ( t , conn , wrapper )
err := vault . RegisterJobs ( context . Background (), sche , rw , rw , kms )
require . NoError ( t , err )
2022-08-23 17:27:56 +01:00
repoFn := func ( o ... target . Option ) ( * target . Repository , error ) {
2022-08-23 18:44:10 +01:00
return target . NewRepository ( ctx , rw , rw , kms )
2022-01-05 14:15:38 -08:00
}
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
2022-06-20 18:20:17 -07:00
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2022-01-05 14:15:38 -08:00
}
2022-08-09 12:43:38 +00:00
sessionRepoFn := func ( opts ... session . Option ) ( * session . Repository , error ) {
2022-08-24 13:22:03 +00:00
return session . NewRepository ( ctx , rw , rw , kms , opts ... )
2022-01-05 14:15:38 -08:00
}
staticHostRepoFn := func () ( * static . Repository , error ) {
2023-06-06 17:09:08 -04:00
return static . NewRepository ( ctx , rw , rw , kms )
2022-01-05 14:15:38 -08:00
}
2022-06-09 15:35:55 -07:00
vaultCredRepoFn := func () ( * vault . Repository , error ) {
2023-06-06 17:09:08 -04:00
return vault . NewRepository ( ctx , rw , rw , kms , sche )
2022-01-05 14:15:38 -08:00
}
2022-06-09 15:35:55 -07:00
staticCredRepoFn := func () ( * credstatic . Repository , error ) {
return credstatic . NewRepository ( ctx , rw , rw , kms )
}
2022-01-05 14:15:38 -08:00
atRepoFn := func () ( * authtoken . Repository , error ) {
2023-06-06 17:09:08 -04:00
return authtoken . NewRepository ( ctx , rw , rw , kms )
2022-01-05 14:15:38 -08:00
}
2023-04-24 19:27:41 -04:00
pluginHostRepoFn := func () ( * hostplugin . Repository , error ) {
2023-06-06 17:09:08 -04:00
return hostplugin . NewRepository ( ctx , rw , rw , kms , sche , map [ string ] plgpb . HostPluginServiceClient {})
2022-01-05 14:15:38 -08:00
}
2024-02-01 08:58:56 -08:00
targetAliasRepoFn := func () ( * talias . Repository , error ) {
return talias . NewRepository ( ctx , rw , rw , kms )
}
2022-01-05 14:15:38 -08:00
org , proj := iam . TestScopes ( t , iamRepo )
at := authtoken . TestAuthToken ( t , conn , kms , org . GetPublicId ())
ctx = auth . NewVerifierContext ( requests . NewRequestContext ( ctx ),
iamRepoFn ,
atRepoFn ,
serversRepoFn ,
kms ,
& authpb . RequestInfo {
Token : at . GetToken (),
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
PublicId : at . GetPublicId (),
})
r := iam . TestRole ( t , conn , proj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2022-01-05 14:15:38 -08:00
2025-01-09 10:26:37 -08:00
workerRPCGracePeriod := new ( atomic . Int64 )
workerRPCGracePeriod . Store ( int64 ( server . DefaultLiveness ))
s , err := targets . NewService ( ctx , kms , repoFn , iamRepoFn , serversRepoFn , sessionRepoFn , pluginHostRepoFn , staticHostRepoFn , vaultCredRepoFn , staticCredRepoFn , targetAliasRepoFn , nil , workerRPCGracePeriod , 1000 , nil )
2022-01-05 14:15:38 -08:00
require . NoError ( t , err )
hc := static . TestCatalogs ( t , conn , proj . GetPublicId (), 1 )[ 0 ]
h := static . TestHosts ( t , conn , hc . GetPublicId (), 1 )[ 0 ]
shs := static . TestSets ( t , conn , hc . GetPublicId (), 1 )[ 0 ]
_ = static . TestSetMembers ( t , conn , shs . GetPublicId (), [] * static . Host { h })
v := vault . NewTestVaultServer ( t )
v . AddKVPolicy ( t )
sec , tok := v . CreateToken ( t , vault . WithPolicies ([] string { "default" , "boundary-controller" , "secret" }))
2022-06-09 15:35:55 -07:00
vaultStore := vault . TestCredentialStore ( t , conn , wrapper , proj . GetPublicId (), v . Addr , tok , sec . Auth . Accessor )
2023-12-01 16:16:19 -08:00
credLibService , err := credentiallibraries . NewService ( ctx , iamRepoFn , vaultCredRepoFn , 1000 )
2022-01-05 14:15:38 -08:00
require . NoError ( t , err )
// Create secret in vault with default username and password fields
defaultUserPass := v . CreateKVSecret ( t , "default-userpass" , [] byte ( `{"data": {"username": "my-user", "password": "my-pass"}}` ))
require . NotNil ( t , defaultUserPass )
2022-06-27 14:03:12 -07:00
clsRespUsernamePassword , err := credLibService . CreateCredentialLibrary ( ctx , & pbs . CreateCredentialLibraryRequest { Item : & credlibpb . CredentialLibrary {
2022-06-09 15:35:55 -07:00
CredentialStoreId : vaultStore . GetPublicId (),
2022-06-27 14:03:12 -07:00
Name : wrapperspb . String ( "Usernamepassword Library" ),
Description : wrapperspb . String ( "Usernamepassword Library Description" ),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2022-06-09 15:35:55 -07:00
Attrs : & credlibpb . CredentialLibrary_VaultCredentialLibraryAttributes {
VaultCredentialLibraryAttributes : & credlibpb . VaultCredentialLibraryAttributes {
2022-04-06 15:29:00 -04:00
Path : wrapperspb . String ( path . Join ( "secret" , "data" , "default-userpass" )),
HttpMethod : wrapperspb . String ( "GET" ),
},
},
2022-06-13 09:01:01 -07:00
CredentialType : "username_password" ,
2022-01-05 14:15:38 -08:00
}})
require . NoError ( t , err )
2022-06-09 15:35:55 -07:00
clsRespUnspecified , err := credLibService . CreateCredentialLibrary ( ctx , & pbs . CreateCredentialLibraryRequest { Item : & credlibpb . CredentialLibrary {
CredentialStoreId : vaultStore . GetPublicId (),
2022-01-05 14:15:38 -08:00
Name : wrapperspb . String ( "Unspecified Library" ),
Description : wrapperspb . String ( "Unspecified Library Description" ),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2022-06-09 15:35:55 -07:00
Attrs : & credlibpb . CredentialLibrary_VaultCredentialLibraryAttributes {
VaultCredentialLibraryAttributes : & credlibpb . VaultCredentialLibraryAttributes {
2022-04-06 15:29:00 -04:00
Path : wrapperspb . String ( path . Join ( "secret" , "data" , "default-userpass" )),
HttpMethod : wrapperspb . String ( "GET" ),
},
},
2022-01-05 14:15:38 -08:00
}})
require . NoError ( t , err )
// Create secret in vault with non default username and password fields
nonDefaultUserPass := v . CreateKVSecret ( t , "non-default-userpass" , [] byte ( `{"data": {"non-default-user": "my-user", "non-default-pass": "my-pass"}}` ))
require . NotNil ( t , nonDefaultUserPass )
2022-06-27 14:03:12 -07:00
clsRespUsernamePasswordWithMapping , err := credLibService . CreateCredentialLibrary ( ctx , & pbs . CreateCredentialLibraryRequest { Item : & credlibpb . CredentialLibrary {
2022-06-09 15:35:55 -07:00
CredentialStoreId : vaultStore . GetPublicId (),
2022-06-27 14:03:12 -07:00
Name : wrapperspb . String ( "Usernamepassword Mapping Library" ),
Description : wrapperspb . String ( "Usernamepassword Mapping Library Description" ),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2022-06-09 15:35:55 -07:00
Attrs : & credlibpb . CredentialLibrary_VaultCredentialLibraryAttributes {
VaultCredentialLibraryAttributes : & credlibpb . VaultCredentialLibraryAttributes {
2022-04-06 15:29:00 -04:00
Path : wrapperspb . String ( path . Join ( "secret" , "data" , "non-default-userpass" )),
HttpMethod : wrapperspb . String ( "GET" ),
},
},
2022-06-13 09:01:01 -07:00
CredentialType : "username_password" ,
2022-01-05 14:15:38 -08:00
CredentialMappingOverrides : & structpb . Struct { Fields : map [ string ] * structpb . Value {
"username_attribute" : structpb . NewStringValue ( "non-default-user" ),
"password_attribute" : structpb . NewStringValue ( "non-default-pass" ),
}},
}})
require . NoError ( t , err )
2022-06-09 15:35:55 -07:00
staticStore := credstatic . TestCredentialStore ( t , conn , wrapper , proj . GetPublicId ())
2023-11-29 16:29:55 -08:00
credService , err := credentials . NewService ( ctx , iamRepoFn , staticCredRepoFn , 1000 )
2022-06-09 15:35:55 -07:00
require . NoError ( t , err )
2022-07-19 10:31:53 -07:00
upCredResp , err := credService . CreateCredential ( ctx , & pbs . CreateCredentialRequest { Item : & credpb . Credential {
2022-06-09 15:35:55 -07:00
CredentialStoreId : staticStore . GetPublicId (),
2023-11-02 16:03:47 -04:00
Type : credential . UsernamePasswordSubtype . String (),
2022-06-09 15:35:55 -07:00
Name : wrapperspb . String ( "Cred Name" ),
Description : wrapperspb . String ( "Cred Description" ),
Attrs : & credpb . Credential_UsernamePasswordAttributes {
UsernamePasswordAttributes : & credpb . UsernamePasswordAttributes {
Username : wrapperspb . String ( "static-username" ),
Password : wrapperspb . String ( "static-password" ),
},
},
}})
require . NoError ( t , err )
2022-07-19 10:31:53 -07:00
require . NotNil ( t , upCredResp )
sshPkCredResp , err := credService . CreateCredential ( ctx , & pbs . CreateCredentialRequest { Item : & credpb . Credential {
CredentialStoreId : staticStore . GetPublicId (),
2023-11-02 16:03:47 -04:00
Type : credential . SshPrivateKeySubtype . String (),
2022-07-19 10:31:53 -07:00
Name : wrapperspb . String ( "Cred SSH Name" ),
Description : wrapperspb . String ( "Cred SSH Description" ),
Attrs : & credpb . Credential_SshPrivateKeyAttributes {
SshPrivateKeyAttributes : & credpb . SshPrivateKeyAttributes {
Username : wrapperspb . String ( "static-username" ),
PrivateKey : wrapperspb . String ( string ( testdata . PEMBytes [ "ed25519" ])),
},
},
}})
require . NoError ( t , err )
require . NotNil ( t , sshPkCredResp )
2022-08-08 15:15:03 -04:00
sshPkWithPassCredResp , err := credService . CreateCredential ( ctx , & pbs . CreateCredentialRequest { Item : & credpb . Credential {
CredentialStoreId : staticStore . GetPublicId (),
2023-11-02 16:03:47 -04:00
Type : credential . SshPrivateKeySubtype . String (),
2022-08-08 15:15:03 -04:00
Name : wrapperspb . String ( "Cred SSH With Pass Name" ),
Description : wrapperspb . String ( "Cred SSH Description" ),
Attrs : & credpb . Credential_SshPrivateKeyAttributes {
SshPrivateKeyAttributes : & credpb . SshPrivateKeyAttributes {
Username : wrapperspb . String ( "static-username" ),
PrivateKey : wrapperspb . String ( string ( testdata . PEMEncryptedKeys [ 0 ]. PEMBytes )),
PrivateKeyPassphrase : wrapperspb . String ( testdata . PEMEncryptedKeys [ 0 ]. EncryptionKey ),
},
},
}})
require . NoError ( t , err )
require . NotNil ( t , sshPkWithPassCredResp )
// Create secret in vault with default username and private key fields
2022-07-19 10:31:53 -07:00
defaultSshPrivateKey := v . CreateKVSecret ( t , "default-sshpk" , [] byte ( `{"data": {"username": "my-user", "private_key": "my-pk"}}` ))
require . NotNil ( t , defaultSshPrivateKey )
clsRespSshPrivateKey , err := credLibService . CreateCredentialLibrary ( ctx , & pbs . CreateCredentialLibraryRequest { Item : & credlibpb . CredentialLibrary {
CredentialStoreId : vaultStore . GetPublicId (),
Name : wrapperspb . String ( "SSH Private Key Library" ),
Description : wrapperspb . String ( "SSH Private Key Library Description" ),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2022-07-19 10:31:53 -07:00
Attrs : & credlibpb . CredentialLibrary_VaultCredentialLibraryAttributes {
VaultCredentialLibraryAttributes : & credlibpb . VaultCredentialLibraryAttributes {
Path : wrapperspb . String ( path . Join ( "secret" , "data" , "default-sshpk" )),
HttpMethod : wrapperspb . String ( "GET" ),
},
},
CredentialType : "ssh_private_key" ,
}})
require . NoError ( t , err )
2022-08-08 15:15:03 -04:00
// Create secret in vault with non default username and private key fields
2022-07-19 10:31:53 -07:00
nonDefaultSshPrivateKey := v . CreateKVSecret ( t , "non-default-sshpk" , [] byte ( `{"data": {"non-default-user": "my-user", "non-default-pk": "my-special-pk"}}` ))
require . NotNil ( t , nonDefaultSshPrivateKey )
clsRespSshPrivateKeyWithMapping , err := credLibService . CreateCredentialLibrary ( ctx , & pbs . CreateCredentialLibraryRequest { Item : & credlibpb . CredentialLibrary {
CredentialStoreId : vaultStore . GetPublicId (),
Name : wrapperspb . String ( "SSH Private Key Mapping Library" ),
Description : wrapperspb . String ( "SSH Private Key Mapping Library Description" ),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2022-07-19 10:31:53 -07:00
Attrs : & credlibpb . CredentialLibrary_VaultCredentialLibraryAttributes {
VaultCredentialLibraryAttributes : & credlibpb . VaultCredentialLibraryAttributes {
Path : wrapperspb . String ( path . Join ( "secret" , "data" , "non-default-sshpk" )),
HttpMethod : wrapperspb . String ( "GET" ),
},
},
CredentialType : "ssh_private_key" ,
CredentialMappingOverrides : & structpb . Struct { Fields : map [ string ] * structpb . Value {
"username_attribute" : structpb . NewStringValue ( "non-default-user" ),
"private_key_attribute" : structpb . NewStringValue ( "non-default-pk" ),
}},
}})
require . NoError ( t , err )
2022-06-09 15:35:55 -07:00
2022-08-08 15:15:03 -04:00
// Create secret in vault with default username, private key and passphrase fields
defaultSshPrivateKeyWithPass := v . CreateKVSecret ( t , "default-sshpk-with-pass" , [] byte ( `{"data": {"username": "my-user", "private_key": "my-pk", "private_key_passphrase": "my-pass"}}` ))
require . NotNil ( t , defaultSshPrivateKeyWithPass )
clsRespSshPrivateKeyWithPass , err := credLibService . CreateCredentialLibrary ( ctx , & pbs . CreateCredentialLibraryRequest { Item : & credlibpb . CredentialLibrary {
CredentialStoreId : vaultStore . GetPublicId (),
Name : wrapperspb . String ( "SSH Private Key With Passphrase Library" ),
Description : wrapperspb . String ( "SSH Private Key Library Description" ),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2022-08-08 15:15:03 -04:00
Attrs : & credlibpb . CredentialLibrary_VaultCredentialLibraryAttributes {
VaultCredentialLibraryAttributes : & credlibpb . VaultCredentialLibraryAttributes {
Path : wrapperspb . String ( path . Join ( "secret" , "data" , "default-sshpk-with-pass" )),
HttpMethod : wrapperspb . String ( "GET" ),
},
},
CredentialType : "ssh_private_key" ,
}})
require . NoError ( t , err )
require . NotNil ( t , clsRespSshPrivateKeyWithPass )
// Create secret in vault with non default username, private key and private key passphrase fields
nonDefaultSshPrivateKeyWithPass := v . CreateKVSecret ( t , "non-default-sshpk-with-pass" , [] byte ( `{"data": {"non-default-user": "my-user", "non-default-pk": "my-special-pk", "embedded": {"secret-pass": "my-special-pass"}}}}` ))
require . NotNil ( t , nonDefaultSshPrivateKeyWithPass )
clsRespSshPrivateKeyWithPassWithMapping , err := credLibService . CreateCredentialLibrary ( ctx , & pbs . CreateCredentialLibraryRequest { Item : & credlibpb . CredentialLibrary {
CredentialStoreId : vaultStore . GetPublicId (),
Name : wrapperspb . String ( "SSH Private Key With Passphrase Mapping Library" ),
Description : wrapperspb . String ( "SSH Private Key Mapping Library Description" ),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2022-08-08 15:15:03 -04:00
Attrs : & credlibpb . CredentialLibrary_VaultCredentialLibraryAttributes {
VaultCredentialLibraryAttributes : & credlibpb . VaultCredentialLibraryAttributes {
Path : wrapperspb . String ( path . Join ( "secret" , "data" , "non-default-sshpk-with-pass" )),
HttpMethod : wrapperspb . String ( "GET" ),
},
},
CredentialType : "ssh_private_key" ,
CredentialMappingOverrides : & structpb . Struct { Fields : map [ string ] * structpb . Value {
"username_attribute" : structpb . NewStringValue ( "/data/non-default-user" ),
"private_key_attribute" : structpb . NewStringValue ( "/data/non-default-pk" ),
"private_key_passphrase_attribute" : structpb . NewStringValue ( "/data/embedded/secret-pass" ),
}},
}})
require . NoError ( t , err )
require . NotNil ( t , clsRespSshPrivateKeyWithPassWithMapping )
2022-01-05 14:15:38 -08:00
cases := [] struct {
2024-12-30 14:16:39 -05:00
name string
hostSourceId string
credSourceId string
wantedHostId string
wantedEndpoint string
wantedCred * pb . SessionCredential
wantedConnectionLimit int32
2022-01-05 14:15:38 -08:00
}{
{
2022-06-09 15:35:55 -07:00
name : "vault-unspecified" ,
2022-01-05 14:15:38 -08:00
hostSourceId : shs . GetPublicId (),
2022-06-09 15:35:55 -07:00
credSourceId : clsRespUnspecified . GetItem (). GetId (),
2022-01-05 14:15:38 -08:00
wantedHostId : h . GetPublicId (),
wantedEndpoint : h . GetAddress (),
2022-06-09 15:35:55 -07:00
wantedCred : & pb . SessionCredential {
CredentialSource : & pb . CredentialSource {
Id : clsRespUnspecified . GetItem (). GetId (),
Name : clsRespUnspecified . GetItem (). GetName (). GetValue (),
Description : clsRespUnspecified . GetItem (). GetDescription (). GetValue (),
CredentialStoreId : vaultStore . GetPublicId (),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2022-06-09 15:35:55 -07:00
},
},
2024-12-30 14:16:39 -05:00
wantedConnectionLimit : 1 ,
2022-01-05 14:15:38 -08:00
},
{
2022-06-27 14:03:12 -07:00
name : "vault-usernamepassword" ,
2022-01-05 14:15:38 -08:00
hostSourceId : shs . GetPublicId (),
2022-06-27 14:03:12 -07:00
credSourceId : clsRespUsernamePassword . GetItem (). GetId (),
2022-01-05 14:15:38 -08:00
wantedHostId : h . GetPublicId (),
wantedEndpoint : h . GetAddress (),
2022-06-09 15:35:55 -07:00
wantedCred : & pb . SessionCredential {
CredentialSource : & pb . CredentialSource {
2022-06-27 14:03:12 -07:00
Id : clsRespUsernamePassword . GetItem (). GetId (),
Name : clsRespUsernamePassword . GetItem (). GetName (). GetValue (),
Description : clsRespUsernamePassword . GetItem (). GetDescription (). GetValue (),
2022-06-09 15:35:55 -07:00
CredentialStoreId : vaultStore . GetPublicId (),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2023-10-18 14:48:44 -07:00
CredentialType : string ( globals . UsernamePasswordCredentialType ),
2022-06-09 15:35:55 -07:00
},
Credential : func () * structpb . Struct {
2022-10-25 18:29:38 -05:00
data := map [ string ] any {
2022-06-09 15:35:55 -07:00
"password" : "my-pass" ,
"username" : "my-user" ,
}
st , err := structpb . NewStruct ( data )
require . NoError ( t , err )
return st
}(),
},
2024-12-30 14:16:39 -05:00
wantedConnectionLimit : 10 ,
2022-01-05 14:15:38 -08:00
},
{
2022-06-27 14:03:12 -07:00
name : "vault-UsernamePassword-with-mapping" ,
2022-01-05 14:15:38 -08:00
hostSourceId : shs . GetPublicId (),
2022-06-27 14:03:12 -07:00
credSourceId : clsRespUsernamePasswordWithMapping . GetItem (). GetId (),
2022-01-05 14:15:38 -08:00
wantedHostId : h . GetPublicId (),
wantedEndpoint : h . GetAddress (),
2022-06-09 15:35:55 -07:00
wantedCred : & pb . SessionCredential {
CredentialSource : & pb . CredentialSource {
2022-06-27 14:03:12 -07:00
Id : clsRespUsernamePasswordWithMapping . GetItem (). GetId (),
Name : clsRespUsernamePasswordWithMapping . GetItem (). GetName (). GetValue (),
Description : clsRespUsernamePasswordWithMapping . GetItem (). GetDescription (). GetValue (),
2022-06-09 15:35:55 -07:00
CredentialStoreId : vaultStore . GetPublicId (),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2023-10-18 14:48:44 -07:00
CredentialType : string ( globals . UsernamePasswordCredentialType ),
2022-06-09 15:35:55 -07:00
},
Credential : func () * structpb . Struct {
2022-10-25 18:29:38 -05:00
data := map [ string ] any {
2022-06-09 15:35:55 -07:00
"password" : "my-pass" ,
"username" : "my-user" ,
}
st , err := structpb . NewStruct ( data )
require . NoError ( t , err )
return st
}(),
},
2024-12-30 14:16:39 -05:00
wantedConnectionLimit : 100 ,
2022-06-09 15:35:55 -07:00
},
{
2022-06-27 14:03:12 -07:00
name : "static-UsernamePassword" ,
2022-06-09 15:35:55 -07:00
hostSourceId : shs . GetPublicId (),
2022-07-19 10:31:53 -07:00
credSourceId : upCredResp . GetItem (). GetId (),
2022-06-09 15:35:55 -07:00
wantedHostId : h . GetPublicId (),
wantedEndpoint : h . GetAddress (),
wantedCred : & pb . SessionCredential {
CredentialSource : & pb . CredentialSource {
2022-07-19 10:31:53 -07:00
Id : upCredResp . GetItem (). GetId (),
Name : upCredResp . GetItem (). GetName (). GetValue (),
Description : upCredResp . GetItem (). GetDescription (). GetValue (),
2022-06-09 15:35:55 -07:00
CredentialStoreId : staticStore . GetPublicId (),
2023-11-02 16:03:47 -04:00
Type : credstatic . Subtype . String (),
2023-10-18 14:48:44 -07:00
CredentialType : string ( globals . UsernamePasswordCredentialType ),
2022-06-09 15:35:55 -07:00
},
Credential : func () * structpb . Struct {
2022-10-25 18:29:38 -05:00
data := map [ string ] any {
2022-06-09 15:35:55 -07:00
"password" : "static-password" ,
"username" : "static-username" ,
}
st , err := structpb . NewStruct ( data )
require . NoError ( t , err )
return st
}(),
},
2024-12-30 14:16:39 -05:00
wantedConnectionLimit : 1000 ,
2022-01-05 14:15:38 -08:00
},
2022-07-19 10:31:53 -07:00
{
name : "static-ssh-private-key" ,
hostSourceId : shs . GetPublicId (),
credSourceId : sshPkCredResp . GetItem (). GetId (),
wantedHostId : h . GetPublicId (),
wantedEndpoint : h . GetAddress (),
wantedCred : & pb . SessionCredential {
CredentialSource : & pb . CredentialSource {
Id : sshPkCredResp . GetItem (). GetId (),
Name : sshPkCredResp . GetItem (). GetName (). GetValue (),
Description : sshPkCredResp . GetItem (). GetDescription (). GetValue (),
CredentialStoreId : staticStore . GetPublicId (),
2023-11-02 16:03:47 -04:00
Type : credstatic . Subtype . String (),
2023-10-18 14:48:44 -07:00
CredentialType : string ( globals . SshPrivateKeyCredentialType ),
2022-07-19 10:31:53 -07:00
},
Credential : func () * structpb . Struct {
2022-10-25 18:29:38 -05:00
data := map [ string ] any {
2022-07-19 10:31:53 -07:00
"private_key" : string ( testdata . PEMBytes [ "ed25519" ]),
"username" : "static-username" ,
}
st , err := structpb . NewStruct ( data )
require . NoError ( t , err )
return st
}(),
},
2024-12-30 14:16:39 -05:00
wantedConnectionLimit : 10000 ,
2022-07-19 10:31:53 -07:00
},
{
name : "vault-ssh-private-key" ,
hostSourceId : shs . GetPublicId (),
credSourceId : clsRespSshPrivateKey . GetItem (). GetId (),
wantedHostId : h . GetPublicId (),
wantedEndpoint : h . GetAddress (),
wantedCred : & pb . SessionCredential {
CredentialSource : & pb . CredentialSource {
Id : clsRespSshPrivateKey . GetItem (). GetId (),
Name : clsRespSshPrivateKey . GetItem (). GetName (). GetValue (),
Description : clsRespSshPrivateKey . GetItem (). GetDescription (). GetValue (),
CredentialStoreId : vaultStore . GetPublicId (),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2023-10-18 14:48:44 -07:00
CredentialType : string ( globals . SshPrivateKeyCredentialType ),
2022-07-19 10:31:53 -07:00
},
Credential : func () * structpb . Struct {
2022-10-25 18:29:38 -05:00
data := map [ string ] any {
2022-07-19 10:31:53 -07:00
"private_key" : "my-pk" ,
"username" : "my-user" ,
}
st , err := structpb . NewStruct ( data )
require . NoError ( t , err )
return st
}(),
},
2024-12-30 14:16:39 -05:00
wantedConnectionLimit : 50000 ,
2022-07-19 10:31:53 -07:00
},
{
name : "vault-ssh-private-key-with-mapping" ,
hostSourceId : shs . GetPublicId (),
credSourceId : clsRespSshPrivateKeyWithMapping . GetItem (). GetId (),
wantedHostId : h . GetPublicId (),
wantedEndpoint : h . GetAddress (),
wantedCred : & pb . SessionCredential {
CredentialSource : & pb . CredentialSource {
Id : clsRespSshPrivateKeyWithMapping . GetItem (). GetId (),
Name : clsRespSshPrivateKeyWithMapping . GetItem (). GetName (). GetValue (),
Description : clsRespSshPrivateKeyWithMapping . GetItem (). GetDescription (). GetValue (),
CredentialStoreId : vaultStore . GetPublicId (),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2023-10-18 14:48:44 -07:00
CredentialType : string ( globals . SshPrivateKeyCredentialType ),
2022-07-19 10:31:53 -07:00
},
Credential : func () * structpb . Struct {
2022-10-25 18:29:38 -05:00
data := map [ string ] any {
2022-07-19 10:31:53 -07:00
"username" : "my-user" ,
"private_key" : "my-special-pk" ,
}
st , err := structpb . NewStruct ( data )
require . NoError ( t , err )
return st
}(),
},
2024-12-30 14:16:39 -05:00
wantedConnectionLimit : 100000 ,
2022-07-19 10:31:53 -07:00
},
2022-08-08 15:15:03 -04:00
{
name : "static-ssh-private-key-with-pass" ,
hostSourceId : shs . GetPublicId (),
credSourceId : sshPkWithPassCredResp . GetItem (). GetId (),
wantedHostId : h . GetPublicId (),
wantedEndpoint : h . GetAddress (),
wantedCred : & pb . SessionCredential {
CredentialSource : & pb . CredentialSource {
Id : sshPkWithPassCredResp . GetItem (). GetId (),
Name : sshPkWithPassCredResp . GetItem (). GetName (). GetValue (),
Description : sshPkWithPassCredResp . GetItem (). GetDescription (). GetValue (),
CredentialStoreId : staticStore . GetPublicId (),
2023-11-02 16:03:47 -04:00
Type : credstatic . Subtype . String (),
2023-10-18 14:48:44 -07:00
CredentialType : string ( globals . SshPrivateKeyCredentialType ),
2022-08-08 15:15:03 -04:00
},
Credential : func () * structpb . Struct {
2022-10-25 18:29:38 -05:00
data := map [ string ] any {
2022-08-08 15:15:03 -04:00
"private_key_passphrase" : testdata . PEMEncryptedKeys [ 0 ]. EncryptionKey ,
"private_key" : string ( testdata . PEMEncryptedKeys [ 0 ]. PEMBytes ),
"username" : "static-username" ,
}
st , err := structpb . NewStruct ( data )
require . NoError ( t , err )
return st
}(),
},
2024-12-30 14:16:39 -05:00
wantedConnectionLimit : 500000 ,
2022-08-08 15:15:03 -04:00
},
{
name : "vault-ssh-private-key-with-pass" ,
hostSourceId : shs . GetPublicId (),
credSourceId : clsRespSshPrivateKeyWithPass . GetItem (). GetId (),
wantedHostId : h . GetPublicId (),
wantedEndpoint : h . GetAddress (),
wantedCred : & pb . SessionCredential {
CredentialSource : & pb . CredentialSource {
Id : clsRespSshPrivateKeyWithPass . GetItem (). GetId (),
Name : clsRespSshPrivateKeyWithPass . GetItem (). GetName (). GetValue (),
Description : clsRespSshPrivateKeyWithPass . GetItem (). GetDescription (). GetValue (),
CredentialStoreId : vaultStore . GetPublicId (),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2023-10-18 14:48:44 -07:00
CredentialType : string ( globals . SshPrivateKeyCredentialType ),
2022-08-08 15:15:03 -04:00
},
Credential : func () * structpb . Struct {
2022-10-25 18:29:38 -05:00
data := map [ string ] any {
2022-08-08 15:15:03 -04:00
"username" : "my-user" ,
"private_key" : "my-pk" ,
"private_key_passphrase" : "my-pass" ,
}
st , err := structpb . NewStruct ( data )
require . NoError ( t , err )
return st
}(),
},
2024-12-30 14:16:39 -05:00
wantedConnectionLimit : 1000000 ,
2022-08-08 15:15:03 -04:00
},
{
name : "vault-ssh-private-key-with-pass-with-mapping" ,
hostSourceId : shs . GetPublicId (),
credSourceId : clsRespSshPrivateKeyWithPassWithMapping . GetItem (). GetId (),
wantedHostId : h . GetPublicId (),
wantedEndpoint : h . GetAddress (),
wantedCred : & pb . SessionCredential {
CredentialSource : & pb . CredentialSource {
Id : clsRespSshPrivateKeyWithPassWithMapping . GetItem (). GetId (),
Name : clsRespSshPrivateKeyWithPassWithMapping . GetItem (). GetName (). GetValue (),
Description : clsRespSshPrivateKeyWithPassWithMapping . GetItem (). GetDescription (). GetValue (),
CredentialStoreId : vaultStore . GetPublicId (),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2023-10-18 14:48:44 -07:00
CredentialType : string ( globals . SshPrivateKeyCredentialType ),
2022-08-08 15:15:03 -04:00
},
Credential : func () * structpb . Struct {
2022-10-25 18:29:38 -05:00
data := map [ string ] any {
2022-08-08 15:15:03 -04:00
"username" : "my-user" ,
"private_key" : "my-special-pk" ,
"private_key_passphrase" : "my-special-pass" ,
}
st , err := structpb . NewStruct ( data )
require . NoError ( t , err )
return st
}(),
},
2024-12-30 14:16:39 -05:00
wantedConnectionLimit : - 1 ,
2022-08-08 15:15:03 -04:00
},
2022-01-05 14:15:38 -08:00
}
for _ , tc := range cases {
t . Run ( tc . name , func ( t * testing . T ) {
2022-06-13 08:26:24 -07:00
const defaultPort = 2
2024-12-30 14:16:39 -05:00
tar := tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), tc . name , target . WithDefaultPort ( defaultPort ), target . WithSessionConnectionLimit ( tc . wantedConnectionLimit ))
2022-06-15 08:56:24 -07:00
apiTar , err := s . AddTargetHostSources ( ctx , & pbs . AddTargetHostSourcesRequest {
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
HostSourceIds : [] string { tc . hostSourceId },
2022-01-05 14:15:38 -08:00
})
require . NoError ( t , err )
_ , err = s . AddTargetCredentialSources ( ctx ,
& pbs . AddTargetCredentialSourcesRequest {
2022-07-19 15:16:24 -07:00
Id : tar . GetPublicId (),
BrokeredCredentialSourceIds : [] string { tc . credSourceId },
Version : apiTar . GetItem (). GetVersion (),
2022-01-05 14:15:38 -08:00
})
require . NoError ( t , err )
// Tell our DB that there is a worker ready to serve the data
2022-06-20 18:20:17 -07:00
server . TestKmsWorker ( t , conn , wrapper )
2022-01-05 14:15:38 -08:00
2024-04-06 13:48:47 -07:00
// Generate correlation Id and add it to the context
corId , err := uuid . GenerateUUID ()
require . NoError ( t , err )
ctx , err = event . NewCorrelationIdContext ( ctx , corId )
require . NoError ( t , err )
2022-01-05 14:15:38 -08:00
asRes , err := s . AuthorizeSession ( ctx , & pbs . AuthorizeSessionRequest {
Id : tar . GetPublicId (),
})
require . NoError ( t , err )
want := & pb . SessionAuthorization {
Scope : & scopes . ScopeInfo {
Id : proj . GetPublicId (),
Type : proj . GetType (),
Name : proj . GetName (),
Description : proj . GetDescription (),
ParentScopeId : proj . GetParentId (),
},
2024-12-30 14:16:39 -05:00
TargetId : tar . GetPublicId (),
UserId : at . GetIamUserId (),
HostSetId : tc . hostSourceId ,
HostId : tc . wantedHostId ,
Type : "tcp" ,
Endpoint : fmt . Sprintf ( "tcp://%s:%d" , tc . wantedEndpoint , defaultPort ),
Credentials : [] * pb . SessionCredential { tc . wantedCred },
EndpointPort : uint32 ( defaultPort ),
Expiration : asRes . Item . Expiration ,
ConnectionLimit : tc . wantedConnectionLimit ,
2022-01-05 14:15:38 -08:00
// TODO: validate the contents of the authorization token is what is expected
}
got := asRes . GetItem ()
require . Len ( t , got . GetCredentials (), 1 )
gotCred := got . Credentials [ 0 ]
require . NotNil ( t , gotCred . Secret )
assert . NotEmpty ( t , gotCred . Secret . Raw )
gotCred . Secret = nil
got . AuthorizationToken , got . SessionId , got . CreatedTime = "" , "" , nil
2023-10-31 13:44:17 +00:00
assert . Empty ( t , cmp . Diff (
got ,
want ,
protocmp . Transform (),
cmpopts . SortSlices ( func ( a , b string ) bool {
return a < b
}),
))
2021-09-26 08:17:21 -07:00
})
}
2021-06-22 22:26:26 -04:00
}
func TestAuthorizeSession_Errors ( t * testing . T ) {
2021-09-26 08:17:21 -07:00
ctx := context . Background ()
2023-09-07 11:52:00 -07:00
// This prevents us from running tests in parallel.
2025-01-08 15:18:03 +00:00
server . TestUseCommunityFilterWorkersFn ( t )
2021-06-22 22:26:26 -04:00
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 )
2021-10-22 15:53:18 -07:00
err := vault . RegisterJobs ( context . Background (), sche , rw , rw , kms )
require . NoError ( t , err )
2022-08-23 17:27:56 +01:00
repoFn := func ( o ... target . Option ) ( * target . Repository , error ) {
2022-08-23 18:44:10 +01:00
return target . NewRepository ( ctx , rw , rw , kms )
2021-06-22 22:26:26 -04:00
}
iamRepo := iam . TestRepo ( t , conn , wrapper )
iamRepoFn := func () ( * iam . Repository , error ) {
return iamRepo , nil
}
2022-06-20 18:20:17 -07:00
serversRepoFn := func () ( * server . Repository , error ) {
2023-06-06 17:09:08 -04:00
return server . NewRepository ( ctx , rw , rw , kms )
2021-06-22 22:26:26 -04:00
}
2022-08-09 12:43:38 +00:00
sessionRepoFn := func ( opts ... session . Option ) ( * session . Repository , error ) {
2022-08-24 13:22:03 +00:00
return session . NewRepository ( ctx , rw , rw , kms , opts ... )
2021-06-22 22:26:26 -04:00
}
staticHostRepoFn := func () ( * static . Repository , error ) {
2023-06-06 17:09:08 -04:00
return static . NewRepository ( ctx , rw , rw , kms )
2021-06-22 22:26:26 -04:00
}
2023-04-24 19:27:41 -04:00
pluginHostRepoFn := func () ( * hostplugin . Repository , error ) {
2023-06-06 17:09:08 -04:00
return hostplugin . NewRepository ( ctx , rw , rw , kms , sche , map [ string ] plgpb . HostPluginServiceClient {})
2021-09-26 08:17:21 -07:00
}
2022-06-09 15:35:55 -07:00
vaultCredRepoFn := func () ( * vault . Repository , error ) {
2023-06-06 17:09:08 -04:00
return vault . NewRepository ( ctx , rw , rw , kms , sche )
2021-06-22 22:26:26 -04:00
}
2022-06-09 15:35:55 -07:00
staticCredRepoFn := func () ( * credstatic . Repository , error ) {
return credstatic . NewRepository ( ctx , rw , rw , kms )
}
2021-06-22 22:26:26 -04:00
atRepoFn := func () ( * authtoken . Repository , error ) {
2023-06-06 17:09:08 -04:00
return authtoken . NewRepository ( ctx , rw , rw , kms )
2021-06-22 22:26:26 -04:00
}
2024-02-01 08:58:56 -08:00
targetAliasRepoFn := func () ( * talias . Repository , error ) {
return talias . NewRepository ( ctx , rw , rw , kms )
}
2021-06-22 22:26:26 -04:00
org , proj := iam . TestScopes ( t , iamRepo )
2025-01-09 10:26:37 -08:00
workerRPCGracePeriod := new ( atomic . Int64 )
workerRPCGracePeriod . Store ( int64 ( server . DefaultLiveness ))
s , err := targets . NewService ( ctx , kms , repoFn , iamRepoFn , serversRepoFn , sessionRepoFn , pluginHostRepoFn , staticHostRepoFn , vaultCredRepoFn , staticCredRepoFn , targetAliasRepoFn , nil , workerRPCGracePeriod , 1000 , nil )
2021-06-22 22:26:26 -04:00
require . NoError ( t , err )
// Authorized user gets full permissions
at := authtoken . TestAuthToken ( t , conn , kms , org . GetPublicId ())
2021-09-26 08:17:21 -07:00
ctx = auth . NewVerifierContext ( requests . NewRequestContext ( context . Background ()),
2021-06-22 22:26:26 -04:00
iamRepoFn ,
atRepoFn ,
serversRepoFn ,
kms ,
2021-10-19 17:21:41 -04:00
& authpb . RequestInfo {
2021-06-22 22:26:26 -04:00
Token : at . GetToken (),
2021-10-19 17:21:41 -04:00
TokenFormat : uint32 ( auth . AuthTokenTypeBearer ),
2021-06-22 22:26:26 -04:00
PublicId : at . GetPublicId (),
})
r := iam . TestRole ( t , conn , proj . GetPublicId ())
_ = iam . TestUserRole ( t , conn , r . GetPublicId (), at . GetIamUserId ())
2024-01-17 23:54:49 -08:00
_ = iam . TestRoleGrant ( t , conn , r . GetPublicId (), "ids=*;type=*;actions=*" )
2021-06-22 22:26:26 -04:00
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 )
2022-09-06 07:50:15 -07:00
sec1 , tok1 := v . CreateToken ( t , vault . WithPolicies ([] string { "default" , "database" }))
expiredStore := vault . TestCredentialStore ( t , conn , wrapper , proj . GetPublicId (), v . Addr , tok1 , sec1 . Auth . Accessor )
// Set previous token to expired in the database and revoke in Vault to validate a
// credential store with an expired token is correctly returned over the API
num , err := rw . Exec ( context . Background (), "update credential_vault_token set status = ? where store_id = ?" ,
2022-10-25 18:29:38 -05:00
[] any { vault . ExpiredToken , expiredStore . PublicId })
2022-09-06 07:50:15 -07:00
require . NoError ( t , err )
assert . Equal ( t , 1 , num )
v . RevokeToken ( t , tok1 )
2024-11-01 13:27:40 -04:00
workerExists := func ( tar target . Target ) target . Target {
2022-06-23 12:16:16 -07:00
server . TestKmsWorker ( t , conn , wrapper )
2024-11-01 13:27:40 -04:00
return tar
2021-06-22 22:26:26 -04:00
}
2024-11-01 13:27:40 -04:00
hostSetNoHostExists := func ( tar target . Target ) target . Target {
2021-06-22 22:26:26 -04:00
hc := static . TestCatalogs ( t , conn , proj . GetPublicId (), 1 )[ 0 ]
hs := static . TestSets ( t , conn , hc . GetPublicId (), 1 )[ 0 ]
2024-11-01 13:27:40 -04:00
_ , err := s . AddTargetHostSources ( ctx , & pbs . AddTargetHostSourcesRequest {
2022-06-15 08:56:24 -07:00
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
HostSourceIds : [] string { hs . GetPublicId ()},
2021-06-22 22:26:26 -04:00
})
require . NoError ( t , err )
2024-11-01 13:27:40 -04:00
repo , err := repoFn ()
require . NoError ( t , err )
tar , err = repo . LookupTarget ( ctx , tar . GetPublicId ())
require . NoError ( t , err )
return tar
2021-06-22 22:26:26 -04:00
}
2024-11-01 13:27:40 -04:00
hostExists := func ( tar target . Target ) target . Target {
2021-06-22 22:26:26 -04:00
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 })
2024-11-01 13:27:40 -04:00
_ , err := s . AddTargetHostSources ( ctx , & pbs . AddTargetHostSourcesRequest {
2022-06-15 08:56:24 -07:00
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
HostSourceIds : [] string { hs . GetPublicId ()},
2022-06-13 08:26:24 -07:00
})
require . NoError ( t , err )
2024-11-01 13:27:40 -04:00
hostRepo , err := staticHostRepoFn ()
require . NoError ( t , err )
_ , _ , err = hostRepo . UpdateHost ( ctx , hc . GetProjectId (), h , h . GetVersion (), [] string { "address" })
2022-06-13 08:26:24 -07:00
require . NoError ( t , err )
2024-11-01 13:27:40 -04:00
repo , err := repoFn ()
2022-06-13 08:26:24 -07:00
require . NoError ( t , err )
2024-11-01 13:27:40 -04:00
tar , err = repo . LookupTarget ( ctx , tar . GetPublicId ())
require . NoError ( t , err )
return tar
2022-06-13 08:26:24 -07:00
}
2024-11-01 13:27:40 -04:00
hostWithoutPort := func ( tar target . Target ) target . Target {
2021-06-22 22:26:26 -04:00
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 })
2024-11-01 13:27:40 -04:00
_ , err := s . AddTargetHostSources ( ctx , & pbs . AddTargetHostSourcesRequest {
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
HostSourceIds : [] string { hs . GetPublicId ()},
})
require . NoError ( t , err )
repo , err := repoFn ()
require . NoError ( t , err )
tar , err = repo . LookupTarget ( ctx , tar . GetPublicId ())
require . NoError ( t , err )
return tar
}
ipv4HostWithHostPort := func ( tar target . Target ) target . Target {
hc := static . TestCatalogs ( t , conn , proj . GetPublicId (), 1 )[ 0 ]
h := static . TestHost ( t , conn , hc . GetPublicId (), static . WithAddress ( "8.8.8.8:22" ))
hs := static . TestSets ( t , conn , hc . GetPublicId (), 1 )[ 0 ]
_ = static . TestSetMembers ( t , conn , hs . GetPublicId (), [] * static . Host { h })
_ , err := s . SetTargetHostSources ( ctx , & pbs . SetTargetHostSourcesRequest {
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
HostSourceIds : [] string { hs . GetPublicId ()},
})
require . NoError ( t , err )
repo , err := repoFn ()
require . NoError ( t , err )
tar , err = repo . LookupTarget ( ctx , tar . GetPublicId ())
require . NoError ( t , err )
return tar
}
ipv6HostWithHostPort := func ( tar target . Target ) target . Target {
hc := static . TestCatalogs ( t , conn , proj . GetPublicId (), 1 )[ 0 ]
h := static . TestHost ( t , conn , hc . GetPublicId (), static . WithAddress ( "[2001:4860:4860:0:0:0:0:8888]:22" ))
hs := static . TestSets ( t , conn , hc . GetPublicId (), 1 )[ 0 ]
_ = static . TestSetMembers ( t , conn , hs . GetPublicId (), [] * static . Host { h })
_ , err := s . SetTargetHostSources ( ctx , & pbs . SetTargetHostSourcesRequest {
2022-06-15 08:56:24 -07:00
Id : tar . GetPublicId (),
Version : tar . GetVersion (),
HostSourceIds : [] string { hs . GetPublicId ()},
2021-06-22 22:26:26 -04:00
})
require . NoError ( t , err )
2024-11-01 13:27:40 -04:00
repo , err := repoFn ()
require . NoError ( t , err )
tar , err = repo . LookupTarget ( ctx , tar . GetPublicId ())
require . NoError ( t , err )
return tar
2021-06-22 22:26:26 -04:00
}
2024-11-01 13:27:40 -04:00
libraryExists := func ( tar target . Target ) target . Target {
2023-12-01 16:16:19 -08:00
credService , err := credentiallibraries . NewService ( ctx , iamRepoFn , vaultCredRepoFn , 1000 )
2021-06-22 22:26:26 -04:00
require . NoError ( t , err )
2022-06-09 15:35:55 -07:00
clsResp , err := credService . CreateCredentialLibrary ( ctx , & pbs . CreateCredentialLibraryRequest { Item : & credlibpb . CredentialLibrary {
2021-06-22 22:26:26 -04:00
CredentialStoreId : store . GetPublicId (),
Description : wrapperspb . String ( fmt . Sprintf ( "Library Description for target %q" , tar . GetName ())),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2022-06-09 15:35:55 -07:00
Attrs : & credlibpb . CredentialLibrary_VaultCredentialLibraryAttributes {
VaultCredentialLibraryAttributes : & credlibpb . VaultCredentialLibraryAttributes {
2022-04-06 15:29:00 -04:00
Path : wrapperspb . String ( path . Join ( "database" , "creds" , "opened" )),
},
},
2021-06-22 22:26:26 -04:00
}})
require . NoError ( t , err )
2024-11-01 13:27:40 -04:00
_ , err = s . AddTargetCredentialSources ( ctx ,
2022-06-15 08:56:24 -07:00
& pbs . AddTargetCredentialSourcesRequest {
2022-07-19 15:16:24 -07:00
Id : tar . GetPublicId (),
BrokeredCredentialSourceIds : [] string { clsResp . GetItem (). GetId ()},
Version : tar . GetVersion (),
2021-06-22 22:26:26 -04:00
})
require . NoError ( t , err )
2024-11-01 13:27:40 -04:00
repo , err := repoFn ()
require . NoError ( t , err )
tar , err = repo . LookupTarget ( ctx , tar . GetPublicId ())
require . NoError ( t , err )
return tar
2021-06-22 22:26:26 -04:00
}
2024-11-01 13:27:40 -04:00
misConfiguredlibraryExists := func ( tar target . Target ) target . Target {
2023-12-01 16:16:19 -08:00
credService , err := credentiallibraries . NewService ( ctx , iamRepoFn , vaultCredRepoFn , 1000 )
2021-06-22 22:26:26 -04:00
require . NoError ( t , err )
2022-06-09 15:35:55 -07:00
clsResp , err := credService . CreateCredentialLibrary ( ctx , & pbs . CreateCredentialLibraryRequest { Item : & credlibpb . CredentialLibrary {
2021-06-22 22:26:26 -04:00
CredentialStoreId : store . GetPublicId (),
Description : wrapperspb . String ( fmt . Sprintf ( "Library Description for target %q" , tar . GetName ())),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2022-06-09 15:35:55 -07:00
Attrs : & credlibpb . CredentialLibrary_VaultCredentialLibraryAttributes {
VaultCredentialLibraryAttributes : & credlibpb . VaultCredentialLibraryAttributes {
2022-04-06 15:29:00 -04:00
Path : wrapperspb . String ( "bad path" ),
},
},
2021-06-22 22:26:26 -04:00
}})
require . NoError ( t , err )
2024-11-01 13:27:40 -04:00
_ , err = s . AddTargetCredentialSources ( ctx ,
2022-06-15 08:56:24 -07:00
& pbs . AddTargetCredentialSourcesRequest {
2022-07-19 15:16:24 -07:00
Id : tar . GetPublicId (),
BrokeredCredentialSourceIds : [] string { clsResp . GetItem (). GetId ()},
Version : tar . GetVersion (),
2021-06-22 22:26:26 -04:00
})
require . NoError ( t , err )
2024-11-01 13:27:40 -04:00
repo , err := repoFn ()
require . NoError ( t , err )
tar , err = repo . LookupTarget ( ctx , tar . GetPublicId ())
require . NoError ( t , err )
return tar
2021-06-22 22:26:26 -04:00
}
2024-11-01 13:27:40 -04:00
expiredTokenLibrary := func ( tar target . Target ) target . Target {
2023-12-01 16:16:19 -08:00
credService , err := credentiallibraries . NewService ( ctx , iamRepoFn , vaultCredRepoFn , 1000 )
2022-09-06 07:50:15 -07:00
require . NoError ( t , err )
clsResp , err := credService . CreateCredentialLibrary ( ctx , & pbs . CreateCredentialLibraryRequest { Item : & credlibpb . CredentialLibrary {
CredentialStoreId : expiredStore . GetPublicId (),
Description : wrapperspb . String ( fmt . Sprintf ( "Library Description for target %q" , tar . GetName ())),
2023-11-02 16:03:47 -04:00
Type : vault . GenericLibrarySubtype . String (),
2022-09-06 07:50:15 -07:00
Attrs : & credlibpb . CredentialLibrary_VaultCredentialLibraryAttributes {
VaultCredentialLibraryAttributes : & credlibpb . VaultCredentialLibraryAttributes {
Path : wrapperspb . String ( path . Join ( "database" , "creds" , "opened" )),
},
},
}})
require . NoError ( t , err )
2024-11-01 13:27:40 -04:00
_ , err = s . AddTargetCredentialSources ( ctx ,
2022-09-06 07:50:15 -07:00
& pbs . AddTargetCredentialSourcesRequest {
Id : tar . GetPublicId (),
BrokeredCredentialSourceIds : [] string { clsResp . GetItem (). GetId ()},
Version : tar . GetVersion (),
})
require . NoError ( t , err )
2024-11-01 13:27:40 -04:00
repo , err := repoFn ()
require . NoError ( t , err )
tar , err = repo . LookupTarget ( ctx , tar . GetPublicId ())
require . NoError ( t , err )
return tar
2022-09-06 07:50:15 -07:00
}
2024-04-06 13:48:47 -07:00
// Generate correlation Id and add it to the context
corId , err := uuid . GenerateUUID ()
require . NoError ( t , err )
ctxWithCor , err := event . NewCorrelationIdContext ( ctx , corId )
require . NoError ( t , err )
2021-06-22 22:26:26 -04:00
cases := [] struct {
2023-07-20 11:01:20 -04:00
name string
2024-04-06 13:48:47 -07:00
ctx context . Context
2024-11-01 13:27:40 -04:00
setup [] func ( target . Target ) target . Target
2023-07-20 11:01:20 -04:00
useTargetId bool
wantErr bool
wantErrContains string
2021-06-22 22:26:26 -04:00
}{
{
// This one must be run first since it relies on the DB not having any worker details
2023-07-20 11:01:20 -04:00
name : "no worker" ,
2024-04-06 13:48:47 -07:00
ctx : ctxWithCor ,
2024-11-01 13:27:40 -04:00
setup : [] func ( tcpTarget target . Target ) target . Target { hostExists , libraryExists },
2023-07-20 11:01:20 -04:00
useTargetId : true ,
wantErrContains : "No workers are available to handle this session" ,
},
{
name : "success" ,
2024-04-06 13:48:47 -07:00
ctx : ctxWithCor ,
2024-11-01 13:27:40 -04:00
setup : [] func ( tcpTarget target . Target ) target . Target { workerExists , hostExists , libraryExists },
2023-07-20 11:01:20 -04:00
useTargetId : true ,
2021-06-22 22:26:26 -04:00
},
{
2023-07-20 11:01:20 -04:00
name : "no target" ,
2024-04-06 13:48:47 -07:00
ctx : ctxWithCor ,
2024-11-01 13:27:40 -04:00
setup : [] func ( tcpTarget target . Target ) target . Target { workerExists , hostExists , libraryExists },
2023-07-20 11:01:20 -04:00
useTargetId : false ,
wantErrContains : "Resource not found" ,
2021-06-22 22:26:26 -04:00
},
2022-06-13 08:26:24 -07:00
{
2023-07-20 11:01:20 -04:00
name : "no host port" ,
2024-04-06 13:48:47 -07:00
ctx : ctxWithCor ,
2024-11-01 13:27:40 -04:00
setup : [] func ( tcpTarget target . Target ) target . Target { workerExists , hostWithoutPort , libraryExists },
2023-07-20 11:01:20 -04:00
useTargetId : true ,
2022-06-13 08:26:24 -07:00
},
2024-01-22 10:49:17 -08:00
{
2024-11-01 13:27:40 -04:00
name : "ipv4 target address host port" ,
2024-04-06 13:48:47 -07:00
ctx : ctxWithCor ,
2024-11-01 13:27:40 -04:00
setup : [] func ( tcpTarget target . Target ) target . Target {
workerExists , func ( tcpTarget target . Target ) target . Target {
2024-01-22 10:49:17 -08:00
repo , err := repoFn ()
require . NoError ( t , err )
2024-11-01 13:27:40 -04:00
n , err := repo . DeleteTarget ( ctx , tcpTarget . GetPublicId ())
2024-01-22 10:49:17 -08:00
require . NoError ( t , err )
2024-11-01 13:27:40 -04:00
assert . Equal ( t , 1 , n )
return tcp . TestTarget ( ctx , t , conn , tcpTarget . GetProjectId (), tcpTarget . GetName (), target . WithAddress ( "127.0.0.1:22" ), target . WithDefaultPort ( 22 ))
2024-01-22 10:49:17 -08:00
},
},
2024-11-01 13:27:40 -04:00
wantErrContains : "error when parsing the chosen endpoint host address: unknown: error #0: address contains a port" ,
useTargetId : true ,
},
{
name : "ipv6 target address host port" ,
ctx : ctxWithCor ,
setup : [] func ( tcpTarget target . Target ) target . Target {
workerExists , func ( tcpTarget target . Target ) target . Target {
repo , err := repoFn ()
require . NoError ( t , err )
n , err := repo . DeleteTarget ( ctx , tcpTarget . GetPublicId ())
require . NoError ( t , err )
assert . Equal ( t , 1 , n )
return tcp . TestTarget ( ctx , t , conn , tcpTarget . GetProjectId (), tcpTarget . GetName (), target . WithAddress ( "[2001:4860:4860:0:0:0:0:8888]:22" ), target . WithDefaultPort ( 22 ))
},
},
wantErrContains : "error when parsing the chosen endpoint host address: unknown: error #0: address contains a port" ,
useTargetId : true ,
},
{
name : "ipv4 static host port" ,
ctx : ctxWithCor ,
setup : [] func ( tcpTarget target . Target ) target . Target { ipv4HostWithHostPort },
wantErrContains : "error when parsing the chosen endpoint host address: unknown: error #0: address contains a port" ,
useTargetId : true ,
},
{
name : "ipv6 static host port" ,
ctx : ctxWithCor ,
setup : [] func ( tcpTarget target . Target ) target . Target { ipv6HostWithHostPort },
wantErrContains : "error when parsing the chosen endpoint host address: unknown: error #0: address contains a port" ,
2024-01-22 10:49:17 -08:00
useTargetId : true ,
},
2021-06-22 22:26:26 -04:00
{
2023-07-20 11:01:20 -04:00
name : "no hosts" ,
2024-04-06 13:48:47 -07:00
ctx : ctxWithCor ,
2024-11-01 13:27:40 -04:00
setup : [] func ( tcpTarget target . Target ) target . Target { workerExists , hostSetNoHostExists , libraryExists },
2023-07-20 11:01:20 -04:00
useTargetId : true ,
wantErrContains : "No host sources or address found for given target" ,
2021-06-22 22:26:26 -04:00
},
{
2023-07-20 11:01:20 -04:00
name : "bad library configuration" ,
2024-04-06 13:48:47 -07:00
ctx : ctxWithCor ,
2024-11-01 13:27:40 -04:00
setup : [] func ( tcpTarget target . Target ) target . Target { workerExists , hostExists , misConfiguredlibraryExists },
2023-07-20 11:01:20 -04:00
useTargetId : true ,
wantErrContains : "external system issue: error #3014: Error making API request" ,
2021-06-22 22:26:26 -04:00
},
2022-09-06 07:50:15 -07:00
{
2023-07-20 11:01:20 -04:00
name : "expired token library" ,
2024-04-06 13:48:47 -07:00
ctx : ctxWithCor ,
2024-11-01 13:27:40 -04:00
setup : [] func ( tcpTarget target . Target ) target . Target { workerExists , hostExists , expiredTokenLibrary },
2023-07-20 11:01:20 -04:00
useTargetId : true ,
wantErrContains : "vault.newClient: invalid configuration" ,
2022-09-06 07:50:15 -07:00
},
2024-04-06 13:48:47 -07:00
{
name : "no correaltion id" ,
ctx : ctx ,
2024-11-01 13:27:40 -04:00
setup : [] func ( tcpTarget target . Target ) target . Target { workerExists , hostExists , libraryExists },
2024-04-06 13:48:47 -07:00
useTargetId : true ,
wantErrContains : "authorize session: missing correlation id" ,
},
2021-06-22 22:26:26 -04:00
}
for i , tc := range cases {
t . Run ( tc . name , func ( t * testing . T ) {
2024-04-06 13:48:47 -07:00
ctx := tc . ctx
2023-01-26 10:35:29 -08:00
tar := tcp . TestTarget ( ctx , t , conn , proj . GetPublicId (), fmt . Sprintf ( "test-%d" , i ), target . WithDefaultPort ( 22 ))
2021-06-22 22:26:26 -04:00
for _ , fn := range tc . setup {
2024-11-01 13:27:40 -04:00
tar = fn ( tar )
2021-06-22 22:26:26 -04:00
}
2023-07-20 11:01:20 -04:00
id := tar . GetPublicId ()
if ! tc . useTargetId {
id = "ttcp_bogusid"
}
2021-06-22 22:26:26 -04:00
res , err := s . AuthorizeSession ( ctx , & pbs . AuthorizeSessionRequest {
2023-07-20 11:01:20 -04:00
Id : id ,
2021-06-22 22:26:26 -04:00
})
2024-01-22 10:49:17 -08:00
if tc . wantErrContains != "" {
2021-06-22 22:26:26 -04:00
require . Error ( t , err )
require . Nil ( t , res )
2023-07-20 11:01:20 -04:00
require . ErrorContains ( t , err , tc . wantErrContains )
2021-06-22 22:26:26 -04:00
return
}
require . NoError ( t , err )
require . NotNil ( t , res )
})
}
}
2022-10-25 18:29:38 -05:00
func decodeJsonSecret ( t * testing . T , in string ) map [ string ] any {
2021-06-22 22:26:26 -04:00
t . Helper ()
2022-10-25 18:29:38 -05:00
ret := make ( map [ string ] any )
2021-06-22 22:26:26 -04:00
dec := json . NewDecoder ( base64 . NewDecoder ( base64 . StdEncoding , strings . NewReader ( in )))
require . NoError ( t , dec . Decode ( & ret ))
return ret
}