Sessions Read/List/Cancel API and SDK (#369)
This commit is contained in:
1 parent
f7e48ec836
commit
e937b0ea27
22 files changed
+2852
-130
No files matched your search
@@ -16,6 +16,6 @@ type (
|
||||
PasswordAuthRepoFactory func() (*password.Repository, error)
|
||||
ServersRepoFactory func() (*servers.Repository, error)
|
||||
StaticRepoFactory func() (*static.Repository, error)
|
||||
TargetRepoFactory func() (*target.Repository, error)
|
||||
SessionRepoFactory func() (*session.Repository, error)
|
||||
TargetRepoFactory func() (*target.Repository, error)
|
||||
)
|
||||
@@ -42,9 +42,9 @@ type Controller struct {
|
||||
IamRepoFn common.IamRepoFactory
|
||||
PasswordAuthRepoFn common.PasswordAuthRepoFactory
|
||||
ServersRepoFn common.ServersRepoFactory
|
||||
SessionRepoFn common.SessionRepoFactory
|
||||
StaticHostRepoFn common.StaticRepoFactory
|
||||
TargetRepoFn common.TargetRepoFactory
|
||||
SessionRepoFn common.SessionRepoFactory
|
||||
|
||||
kms *kms.Kms
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/accounts"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/authmethods"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/host_sets"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/sessions"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/targets"
|
||||
"github.com/hashicorp/boundary/sdk/strutil"
|
||||
"github.com/hashicorp/shared-secure-libs/configutil"
|
||||
@@ -169,6 +170,13 @@ func handleGrpcGateway(c *Controller, props HandlerProperties) (http.Handler, er
|
||||
if err := services.RegisterRoleServiceHandlerServer(ctx, mux, rs); err != nil {
|
||||
return nil, fmt.Errorf("failed to register role service handler: %w", err)
|
||||
}
|
||||
ss, err := sessions.NewService(c.SessionRepoFn, c.IamRepoFn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create session handler service: %w", err)
|
||||
}
|
||||
if err := services.RegisterSessionServiceHandlerServer(ctx, mux, ss); err != nil {
|
||||
return nil, fmt.Errorf("failed to register session service handler: %w", err)
|
||||
}
|
||||
|
||||
return mux, nil
|
||||
}
|
||||
|
||||
@@ -93,7 +93,8 @@ func TestHandleImplementedPaths(t *testing.T) {
|
||||
|
||||
for verb, paths := range map[string][]string{
|
||||
"GET": {
|
||||
// new paths
|
||||
"v1/sessions/",
|
||||
"v1/sessions/someid",
|
||||
"v1/scopes",
|
||||
"v1/scopes/someid",
|
||||
"v1/auth-tokens",
|
||||
@@ -119,7 +120,6 @@ func TestHandleImplementedPaths(t *testing.T) {
|
||||
},
|
||||
"POST": {
|
||||
// Creation end points
|
||||
// new paths
|
||||
"v1/scopes",
|
||||
"v1/groups",
|
||||
"v1/roles",
|
||||
@@ -132,6 +132,7 @@ func TestHandleImplementedPaths(t *testing.T) {
|
||||
"v1/targets",
|
||||
|
||||
// custom methods
|
||||
"v1/sessions/someid:cancel",
|
||||
"v1/auth-methods/someid:authenticate",
|
||||
"v1/accounts/someid:set-password",
|
||||
"v1/accounts/someid:change-password",
|
||||
@@ -146,7 +147,6 @@ func TestHandleImplementedPaths(t *testing.T) {
|
||||
"v1/groups/someid:remove-members",
|
||||
},
|
||||
"DELETE": {
|
||||
// new paths
|
||||
"v1/scopes/someid",
|
||||
"v1/users/someid",
|
||||
"v1/roles/someid",
|
||||
@@ -160,7 +160,6 @@ func TestHandleImplementedPaths(t *testing.T) {
|
||||
"v1/targets/someid",
|
||||
},
|
||||
"PATCH": {
|
||||
// new paths
|
||||
"v1/scopes/someid",
|
||||
"v1/users/someid",
|
||||
"v1/roles/someid",
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/boundary/internal/auth"
|
||||
"github.com/hashicorp/boundary/internal/db"
|
||||
pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/sessions"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/common"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers"
|
||||
"github.com/hashicorp/boundary/internal/session"
|
||||
"github.com/hashicorp/boundary/internal/types/action"
|
||||
"github.com/hashicorp/boundary/internal/types/resource"
|
||||
"github.com/hashicorp/boundary/internal/types/scope"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// Service handles request as described by the pbs.SessionServiceServer interface.
|
||||
type Service struct {
|
||||
repoFn common.SessionRepoFactory
|
||||
iamRepoFn common.IamRepoFactory
|
||||
}
|
||||
|
||||
// NewService returns a session service which handles session related requests to boundary.
|
||||
func NewService(repoFn common.SessionRepoFactory, iamRepoFn common.IamRepoFactory) (Service, error) {
|
||||
if repoFn == nil {
|
||||
return Service{}, fmt.Errorf("nil session repository provided")
|
||||
}
|
||||
if iamRepoFn == nil {
|
||||
return Service{}, fmt.Errorf("nil iam repository provided")
|
||||
}
|
||||
return Service{repoFn: repoFn, iamRepoFn: iamRepoFn}, nil
|
||||
}
|
||||
|
||||
var _ pbs.SessionServiceServer = Service{}
|
||||
|
||||
// GetSessions implements the interface pbs.SessionServiceServer.
|
||||
func (s Service) GetSession(ctx context.Context, req *pbs.GetSessionRequest) (*pbs.GetSessionResponse, error) {
|
||||
if err := validateGetRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetId(), action.Read)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
ses, err := s.getFromRepo(ctx, req.GetId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ses.Scope = authResults.Scope
|
||||
return &pbs.GetSessionResponse{Item: ses}, nil
|
||||
}
|
||||
|
||||
// ListSessions implements the interface pbs.SessionServiceServer.
|
||||
func (s Service) ListSessions(ctx context.Context, req *pbs.ListSessionsRequest) (*pbs.ListSessionsResponse, error) {
|
||||
if err := validateListRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetScopeId(), action.List)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
seslist, err := s.listFromRepo(ctx, authResults.Scope.GetId())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, item := range seslist {
|
||||
item.Scope = authResults.Scope
|
||||
}
|
||||
return &pbs.ListSessionsResponse{Items: seslist}, nil
|
||||
}
|
||||
|
||||
// CancelSession implements the interface pbs.SessionServiceServer.
|
||||
func (s Service) CancelSession(ctx context.Context, req *pbs.CancelSessionRequest) (*pbs.CancelSessionResponse, error) {
|
||||
if err := validateCancelRequest(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authResults := s.authResult(ctx, req.GetId(), action.Cancel)
|
||||
if authResults.Error != nil {
|
||||
return nil, authResults.Error
|
||||
}
|
||||
ses, err := s.cancelInRepo(ctx, req.GetId(), req.GetVersion())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ses.Scope = authResults.Scope
|
||||
return &pbs.CancelSessionResponse{Item: ses}, nil
|
||||
}
|
||||
|
||||
func (s Service) getFromRepo(ctx context.Context, id string) (*pb.Session, error) {
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sess, err := repo.LookupSession(ctx, id)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrRecordNotFound) {
|
||||
return nil, handlers.NotFoundErrorf("Session %q doesn't exist.", id)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if sess == nil {
|
||||
return nil, handlers.NotFoundErrorf("Session %q doesn't exist.", id)
|
||||
}
|
||||
return toProto(sess), nil
|
||||
}
|
||||
|
||||
func (s Service) listFromRepo(ctx context.Context, scopeId string) ([]*pb.Session, error) {
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seslist, err := repo.ListSessions(ctx, session.WithScopeId(scopeId))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var outSl []*pb.Session
|
||||
for _, ses := range seslist {
|
||||
outSl = append(outSl, toProto(ses))
|
||||
}
|
||||
return outSl, nil
|
||||
}
|
||||
|
||||
func (s Service) cancelInRepo(ctx context.Context, id string, version uint32) (*pb.Session, error) {
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out, err := repo.CancelSession(ctx, id, version)
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Internal, "Unable to update session: %v.", err)
|
||||
}
|
||||
return toProto(out), nil
|
||||
}
|
||||
|
||||
func (s Service) authResult(ctx context.Context, id string, a action.Type) auth.VerifyResults {
|
||||
res := auth.VerifyResults{}
|
||||
|
||||
var parentId string
|
||||
opts := []auth.Option{auth.WithType(resource.Session), auth.WithAction(a)}
|
||||
switch a {
|
||||
case action.List:
|
||||
parentId = id
|
||||
iamRepo, err := s.iamRepoFn()
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return res
|
||||
}
|
||||
scp, err := iamRepo.LookupScope(ctx, parentId)
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return res
|
||||
}
|
||||
if scp == nil {
|
||||
res.Error = handlers.NotFoundError()
|
||||
return res
|
||||
}
|
||||
case action.Read, action.Cancel:
|
||||
repo, err := s.repoFn()
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return res
|
||||
}
|
||||
t, err := repo.LookupSession(ctx, id)
|
||||
if err != nil {
|
||||
res.Error = err
|
||||
return res
|
||||
}
|
||||
if t == nil {
|
||||
res.Error = handlers.NotFoundError()
|
||||
return res
|
||||
}
|
||||
parentId = t.ScopeId
|
||||
opts = append(opts, auth.WithId(id))
|
||||
default:
|
||||
res.Error = errors.New("unsupported action")
|
||||
return res
|
||||
}
|
||||
opts = append(opts, auth.WithScopeId(parentId))
|
||||
return auth.Verify(ctx, opts...)
|
||||
}
|
||||
|
||||
func toProto(in *session.Session) *pb.Session {
|
||||
out := pb.Session{
|
||||
Id: in.GetPublicId(),
|
||||
ScopeId: in.ScopeId,
|
||||
TargetId: in.TargetId,
|
||||
Version: in.Version,
|
||||
UserId: in.UserId,
|
||||
HostId: in.HostId,
|
||||
HostSetId: in.HostSetId,
|
||||
AuthTokenId: in.AuthTokenId,
|
||||
// TODO: Provide the ServerType and the ServerId when that information becomes relevant in the API.
|
||||
|
||||
CreatedTime: in.CreateTime.GetTimestamp(),
|
||||
UpdatedTime: in.UpdateTime.GetTimestamp(),
|
||||
ExpirationTime: in.ExpirationTime.GetTimestamp(),
|
||||
}
|
||||
if len(in.States) > 0 {
|
||||
out.Status = in.States[0].Status.String()
|
||||
}
|
||||
for _, s := range in.States {
|
||||
sessState := &pb.SessionState{
|
||||
Status: s.Status.String(),
|
||||
}
|
||||
if s.StartTime != nil {
|
||||
sessState.StartTime = s.StartTime.GetTimestamp()
|
||||
}
|
||||
if s.EndTime != nil {
|
||||
sessState.EndTime = s.EndTime.GetTimestamp()
|
||||
}
|
||||
out.States = append(out.States, sessState)
|
||||
}
|
||||
return &out
|
||||
}
|
||||
|
||||
// A validateX method should exist for each method above. These methods do not make calls to any backing service but enforce
|
||||
// requirements on the structure of the request. They verify that:
|
||||
// * The path passed in is correctly formatted
|
||||
// * All required parameters are set
|
||||
// * There are no conflicting parameters provided
|
||||
func validateGetRequest(req *pbs.GetSessionRequest) error {
|
||||
return handlers.ValidateGetRequest(session.SessionPrefix, req, handlers.NoopValidatorFn)
|
||||
}
|
||||
|
||||
func validateListRequest(req *pbs.ListSessionsRequest) error {
|
||||
badFields := map[string]string{}
|
||||
if !handlers.ValidId(scope.Project.Prefix(), req.GetScopeId()) {
|
||||
badFields["scope_id"] = "This field is required to have a properly formatted project scope id."
|
||||
}
|
||||
if len(badFields) > 0 {
|
||||
return handlers.InvalidArgumentErrorf("Improperly formatted identifier.", badFields)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateCancelRequest(req *pbs.CancelSessionRequest) error {
|
||||
badFields := map[string]string{}
|
||||
if !handlers.ValidId(session.SessionPrefix, req.GetId()) {
|
||||
badFields["id"] = "Impropperly formatted identifier."
|
||||
}
|
||||
if req.GetVersion() == 0 {
|
||||
badFields["version"] = "Required field."
|
||||
}
|
||||
if len(badFields) > 0 {
|
||||
return handlers.InvalidArgumentErrorf("Improperly formatted identifier.", badFields)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
package sessions_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
"github.com/hashicorp/boundary/internal/auth"
|
||||
"github.com/hashicorp/boundary/internal/authtoken"
|
||||
"github.com/hashicorp/boundary/internal/db"
|
||||
"github.com/hashicorp/boundary/internal/gen/controller/api/resources/scopes"
|
||||
pb "github.com/hashicorp/boundary/internal/gen/controller/api/resources/sessions"
|
||||
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
||||
"github.com/hashicorp/boundary/internal/host/static"
|
||||
"github.com/hashicorp/boundary/internal/iam"
|
||||
"github.com/hashicorp/boundary/internal/kms"
|
||||
"github.com/hashicorp/boundary/internal/servers/controller/handlers/sessions"
|
||||
"github.com/hashicorp/boundary/internal/session"
|
||||
"github.com/hashicorp/boundary/internal/target"
|
||||
"github.com/hashicorp/boundary/internal/types/scope"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/testing/protocmp"
|
||||
)
|
||||
|
||||
func TestGetSession(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
wrap := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrap)
|
||||
|
||||
iamRepo := iam.TestRepo(t, conn, wrap)
|
||||
|
||||
rw := db.New(conn)
|
||||
sessRepo, err := session.NewRepository(rw, rw, kms)
|
||||
require.NoError(t, err)
|
||||
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iamRepo, nil
|
||||
}
|
||||
sessRepoFn := func() (*session.Repository, error) {
|
||||
return sessRepo, nil
|
||||
}
|
||||
|
||||
o, p := iam.TestScopes(t, iamRepo)
|
||||
at := authtoken.TestAuthToken(t, conn, kms, o.GetPublicId())
|
||||
uId := at.GetIamUserId()
|
||||
hc := static.TestCatalogs(t, conn, p.GetPublicId(), 1)[0]
|
||||
hs := static.TestSets(t, conn, hc.GetPublicId(), 1)[0]
|
||||
h := static.TestHosts(t, conn, hc.GetPublicId(), 1)[0]
|
||||
static.TestSetMembers(t, conn, hs.GetPublicId(), []*static.Host{h})
|
||||
tar := target.TestTcpTarget(t, conn, p.GetPublicId(), "test", target.WithHostSets([]string{hs.GetPublicId()}))
|
||||
|
||||
sess := session.TestSession(t, conn, wrap, session.ComposedOf{
|
||||
UserId: uId,
|
||||
HostId: h.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hs.GetPublicId(),
|
||||
AuthTokenId: at.GetPublicId(),
|
||||
ScopeId: p.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
})
|
||||
|
||||
wireSess := &pb.Session{
|
||||
Id: sess.GetPublicId(),
|
||||
ScopeId: p.GetPublicId(),
|
||||
AuthTokenId: at.GetPublicId(),
|
||||
UserId: at.GetIamUserId(),
|
||||
TargetId: sess.TargetId,
|
||||
HostSetId: sess.HostSetId,
|
||||
HostId: sess.HostId,
|
||||
Version: sess.Version,
|
||||
Status: session.StatusPending.String(),
|
||||
UpdatedTime: sess.UpdateTime.GetTimestamp(),
|
||||
CreatedTime: sess.CreateTime.GetTimestamp(),
|
||||
ExpirationTime: sess.ExpirationTime.GetTimestamp(),
|
||||
Scope: &scopes.ScopeInfo{Id: p.GetPublicId(), Type: scope.Project.String()},
|
||||
States: []*pb.SessionState{{Status: session.StatusPending.String(), StartTime: sess.CreateTime.GetTimestamp()}},
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
scopeId string
|
||||
req *pbs.GetSessionRequest
|
||||
res *pbs.GetSessionResponse
|
||||
errCode codes.Code
|
||||
}{
|
||||
{
|
||||
name: "Get a session",
|
||||
scopeId: sess.ScopeId,
|
||||
req: &pbs.GetSessionRequest{Id: sess.GetPublicId()},
|
||||
res: &pbs.GetSessionResponse{Item: wireSess},
|
||||
errCode: codes.OK,
|
||||
},
|
||||
{
|
||||
name: "Get a non existant Session",
|
||||
req: &pbs.GetSessionRequest{Id: session.SessionPrefix + "_DoesntExis"},
|
||||
res: nil,
|
||||
errCode: codes.NotFound,
|
||||
},
|
||||
{
|
||||
name: "Wrong id prefix",
|
||||
req: &pbs.GetSessionRequest{Id: "j_1234567890"},
|
||||
res: nil,
|
||||
errCode: codes.InvalidArgument,
|
||||
},
|
||||
{
|
||||
name: "space in id",
|
||||
req: &pbs.GetSessionRequest{Id: session.SessionPrefix + "_1 23456789"},
|
||||
res: nil,
|
||||
errCode: codes.InvalidArgument,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
|
||||
s, err := sessions.NewService(sessRepoFn, iamRepoFn)
|
||||
require.NoError(err, "Couldn't create new session service.")
|
||||
|
||||
got, gErr := s.GetSession(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), tc.req)
|
||||
assert.Equal(tc.errCode, status.Code(gErr), "GetSession(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
|
||||
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "GetSession(%q) got response\n%q, wanted\n%q", tc.req, got, tc.res)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestList(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
wrap := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrap)
|
||||
|
||||
iamRepo := iam.TestRepo(t, conn, wrap)
|
||||
|
||||
rw := db.New(conn)
|
||||
sessRepo, err := session.NewRepository(rw, rw, kms)
|
||||
require.NoError(t, err)
|
||||
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iamRepo, nil
|
||||
}
|
||||
sessRepoFn := func() (*session.Repository, error) {
|
||||
return sessRepo, nil
|
||||
}
|
||||
|
||||
_, pNoSessions := iam.TestScopes(t, iamRepo)
|
||||
o, pWithSessions := iam.TestScopes(t, iamRepo)
|
||||
|
||||
at := authtoken.TestAuthToken(t, conn, kms, o.GetPublicId())
|
||||
uId := at.GetIamUserId()
|
||||
hc := static.TestCatalogs(t, conn, pWithSessions.GetPublicId(), 1)[0]
|
||||
hs := static.TestSets(t, conn, hc.GetPublicId(), 1)[0]
|
||||
h := static.TestHosts(t, conn, hc.GetPublicId(), 1)[0]
|
||||
static.TestSetMembers(t, conn, hs.GetPublicId(), []*static.Host{h})
|
||||
tar := target.TestTcpTarget(t, conn, pWithSessions.GetPublicId(), "test", target.WithHostSets([]string{hs.GetPublicId()}))
|
||||
|
||||
var wantSession []*pb.Session
|
||||
for i := 0; i < 10; i++ {
|
||||
sess := session.TestSession(t, conn, wrap, session.ComposedOf{
|
||||
UserId: uId,
|
||||
HostId: h.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hs.GetPublicId(),
|
||||
AuthTokenId: at.GetPublicId(),
|
||||
ScopeId: pWithSessions.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
})
|
||||
|
||||
status, states := convertStates(sess.States)
|
||||
|
||||
wantSession = append(wantSession, &pb.Session{
|
||||
Id: sess.GetPublicId(),
|
||||
ScopeId: pWithSessions.GetPublicId(),
|
||||
AuthTokenId: at.GetPublicId(),
|
||||
UserId: at.GetIamUserId(),
|
||||
TargetId: sess.TargetId,
|
||||
HostSetId: sess.HostSetId,
|
||||
HostId: sess.HostId,
|
||||
Version: sess.Version,
|
||||
UpdatedTime: sess.UpdateTime.GetTimestamp(),
|
||||
CreatedTime: sess.CreateTime.GetTimestamp(),
|
||||
ExpirationTime: sess.ExpirationTime.GetTimestamp(),
|
||||
Scope: &scopes.ScopeInfo{Id: pWithSessions.GetPublicId(), Type: scope.Project.String()},
|
||||
Status: status,
|
||||
States: states,
|
||||
})
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
req *pbs.ListSessionsRequest
|
||||
res *pbs.ListSessionsResponse
|
||||
errCode codes.Code
|
||||
}{
|
||||
{
|
||||
name: "List Many Sessions",
|
||||
req: &pbs.ListSessionsRequest{ScopeId: pWithSessions.GetPublicId()},
|
||||
res: &pbs.ListSessionsResponse{Items: wantSession},
|
||||
errCode: codes.OK,
|
||||
},
|
||||
{
|
||||
name: "List No Sessions",
|
||||
req: &pbs.ListSessionsRequest{ScopeId: pNoSessions.GetPublicId()},
|
||||
res: &pbs.ListSessionsResponse{},
|
||||
errCode: codes.OK,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s, err := sessions.NewService(sessRepoFn, iamRepoFn)
|
||||
require.NoError(t, err, "Couldn't create new session service.")
|
||||
|
||||
got, gErr := s.ListSessions(auth.DisabledAuthTestContext(auth.WithScopeId(tc.req.GetScopeId())), tc.req)
|
||||
assert.Equal(t, tc.errCode, status.Code(gErr), "ListSessions(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
|
||||
assert.Empty(t, cmp.Diff(got, tc.res, protocmp.Transform()), "ListSessions(%q) got response %q, wanted %q", tc.req, got, tc.res)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func convertStates(in []*session.State) (string, []*pb.SessionState) {
|
||||
out := make([]*pb.SessionState, 0, len(in))
|
||||
for _, s := range in {
|
||||
sessState := &pb.SessionState{
|
||||
Status: s.Status.String(),
|
||||
}
|
||||
if s.StartTime != nil {
|
||||
sessState.StartTime = s.StartTime.GetTimestamp()
|
||||
}
|
||||
if s.EndTime != nil {
|
||||
sessState.EndTime = s.EndTime.GetTimestamp()
|
||||
}
|
||||
out = append(out, sessState)
|
||||
}
|
||||
return out[0].Status, out
|
||||
}
|
||||
|
||||
func TestCancel(t *testing.T) {
|
||||
conn, _ := db.TestSetup(t, "postgres")
|
||||
wrap := db.TestWrapper(t)
|
||||
kms := kms.TestKms(t, conn, wrap)
|
||||
|
||||
iamRepo := iam.TestRepo(t, conn, wrap)
|
||||
|
||||
rw := db.New(conn)
|
||||
sessRepo, err := session.NewRepository(rw, rw, kms)
|
||||
require.NoError(t, err)
|
||||
|
||||
iamRepoFn := func() (*iam.Repository, error) {
|
||||
return iamRepo, nil
|
||||
}
|
||||
sessRepoFn := func() (*session.Repository, error) {
|
||||
return sessRepo, nil
|
||||
}
|
||||
|
||||
o, p := iam.TestScopes(t, iamRepo)
|
||||
at := authtoken.TestAuthToken(t, conn, kms, o.GetPublicId())
|
||||
uId := at.GetIamUserId()
|
||||
hc := static.TestCatalogs(t, conn, p.GetPublicId(), 1)[0]
|
||||
hs := static.TestSets(t, conn, hc.GetPublicId(), 1)[0]
|
||||
h := static.TestHosts(t, conn, hc.GetPublicId(), 1)[0]
|
||||
static.TestSetMembers(t, conn, hs.GetPublicId(), []*static.Host{h})
|
||||
tar := target.TestTcpTarget(t, conn, p.GetPublicId(), "test", target.WithHostSets([]string{hs.GetPublicId()}))
|
||||
|
||||
sess := session.TestSession(t, conn, wrap, session.ComposedOf{
|
||||
UserId: uId,
|
||||
HostId: h.GetPublicId(),
|
||||
TargetId: tar.GetPublicId(),
|
||||
HostSetId: hs.GetPublicId(),
|
||||
AuthTokenId: at.GetPublicId(),
|
||||
ScopeId: p.GetPublicId(),
|
||||
Endpoint: "tcp://127.0.0.1:22",
|
||||
})
|
||||
|
||||
wireSess := &pb.Session{
|
||||
Id: sess.GetPublicId(),
|
||||
ScopeId: p.GetPublicId(),
|
||||
AuthTokenId: at.GetPublicId(),
|
||||
UserId: at.GetIamUserId(),
|
||||
TargetId: sess.TargetId,
|
||||
HostSetId: sess.HostSetId,
|
||||
HostId: sess.HostId,
|
||||
Version: sess.Version,
|
||||
CreatedTime: sess.CreateTime.GetTimestamp(),
|
||||
ExpirationTime: sess.ExpirationTime.GetTimestamp(),
|
||||
Scope: &scopes.ScopeInfo{Id: p.GetPublicId(), Type: scope.Project.String()},
|
||||
Status: session.StatusCancelling.String(),
|
||||
}
|
||||
|
||||
version := wireSess.GetVersion()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
scopeId string
|
||||
req *pbs.CancelSessionRequest
|
||||
res *pbs.CancelSessionResponse
|
||||
errCode codes.Code
|
||||
}{
|
||||
{
|
||||
name: "Cancel a session",
|
||||
scopeId: sess.ScopeId,
|
||||
req: &pbs.CancelSessionRequest{Id: sess.GetPublicId()},
|
||||
res: &pbs.CancelSessionResponse{Item: wireSess},
|
||||
errCode: codes.OK,
|
||||
},
|
||||
{
|
||||
name: "Cancel a non existing Session",
|
||||
req: &pbs.CancelSessionRequest{Id: session.SessionPrefix + "_DoesntExis"},
|
||||
res: nil,
|
||||
errCode: codes.NotFound,
|
||||
},
|
||||
{
|
||||
name: "Wrong id prefix",
|
||||
req: &pbs.CancelSessionRequest{Id: "j_1234567890"},
|
||||
res: nil,
|
||||
errCode: codes.InvalidArgument,
|
||||
},
|
||||
{
|
||||
name: "space in id",
|
||||
req: &pbs.CancelSessionRequest{Id: session.SessionPrefix + "_1 23456789"},
|
||||
res: nil,
|
||||
errCode: codes.InvalidArgument,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert, require := assert.New(t), require.New(t)
|
||||
|
||||
s, err := sessions.NewService(sessRepoFn, iamRepoFn)
|
||||
require.NoError(err, "Couldn't create new session service.")
|
||||
|
||||
tc.req.Version = version
|
||||
|
||||
got, gErr := s.CancelSession(auth.DisabledAuthTestContext(auth.WithScopeId(tc.scopeId)), tc.req)
|
||||
assert.Equal(tc.errCode, status.Code(gErr), "GetSession(%+v) got error %v, wanted %v", tc.req, gErr, tc.errCode)
|
||||
|
||||
if tc.res == nil {
|
||||
require.Nil(got)
|
||||
return
|
||||
}
|
||||
tc.res.GetItem().Version = got.GetItem().Version
|
||||
|
||||
// Compare the new cancelling state and then remove it for the rest of the proto comparison
|
||||
assert.True(got.GetItem().GetUpdatedTime().AsTime().After(got.GetItem().GetCreatedTime().AsTime()))
|
||||
assert.Len(got.GetItem().GetStates(), 2)
|
||||
|
||||
wantState := []*pb.SessionState{
|
||||
{
|
||||
Status: session.StatusCancelling.String(),
|
||||
StartTime: got.GetItem().GetUpdatedTime(),
|
||||
},
|
||||
{
|
||||
Status: session.StatusPending.String(),
|
||||
StartTime: got.GetItem().GetCreatedTime(),
|
||||
EndTime: got.GetItem().GetUpdatedTime(),
|
||||
},
|
||||
}
|
||||
assert.Empty(cmp.Diff(got.GetItem().GetStates(), wantState, protocmp.Transform()), "GetSession(%q) states")
|
||||
got.GetItem().States = nil
|
||||
got.GetItem().UpdatedTime = nil
|
||||
|
||||
assert.Empty(cmp.Diff(got, tc.res, protocmp.Transform()), "GetSession(%q) got response\n%q, wanted\n%q", tc.req, got, tc.res)
|
||||
|
||||
if tc.req != nil {
|
||||
require.NotNil(got)
|
||||
version = got.GetItem().GetVersion()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user