session

package
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2020 License: MPL-2.0 Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// SessionPrefix for session PK ids
	SessionPrefix = "s"

	// StatePrefix for state PK ids
	StatePrefix = "ss"

	// ConnectionPrefix for connection PK ids
	ConnectionPrefix = "sc"

	// ConnectionStatePrefix for connection state PK ids
	ConnectionStatePrefix = "scs"
)

Variables

View Source
var (
	// ErrInvalidStateForOperation indicates the session's state does not allow the
	// operation.
	ErrInvalidStateForOperation = errors.New("state is invalid for operation")

	// ErrSessionNotPending indicates that a session cannot be activated
	// because it's not in a pending state.
	ErrSessionNotPending = errors.New("session is not in a pending state")

	// ErrOpenConnection indicates that a session can not be terminated because
	// it has open connections.
	ErrOpenConnection = errors.New("session has open connections")
)

Errors returned from this package may be tested against these errors with errors.Is.

Functions

func DeriveED25519Key

func DeriveED25519Key(wrapper wrapping.Wrapper, userId, jobId string) (ed25519.PublicKey, ed25519.PrivateKey, error)

DeriveED25519Key generates a key based on the scope's session DEK, the requesting user, and the generated job ID.

func TestCert

func TestCert(wrapper wrapping.Wrapper, userId, jobId string) (ed25519.PrivateKey, []byte, error)

TestCert is a temporary test func that intentionally doesn't take testing.T as a parameter. It's currently used in controller.jobTestingHandler() and should be deprecated once that function is refactored to use sessions properly.

func TestTofu

func TestTofu(t *testing.T) []byte

TestTofu will create a test "trust on first use" token

func TestWorker

func TestWorker(t *testing.T, conn *gorm.DB, wrapper wrapping.Wrapper) *servers.Server

Types

type Cloneable

type Cloneable interface {
	Clone() interface{}
}

Clonable provides a cloning interface

type CloseConnectionResp

type CloseConnectionResp struct {
	Connection       *Connection
	ConnectionStates []*ConnectionState
}

CloseConnectionRep is just a wrapper for the response from CloseConnections. It wraps the connection and its states for each connection closed.

type CloseWith

type CloseWith struct {
	ConnectionId string
	BytesUp      uint64
	BytesDown    uint64
	ClosedReason ClosedReason
}

CloseWith defines the boundary data that is saved in the repo when the worker closes a connection between the client and the endpoint.

type ClosedReason

type ClosedReason string

ClosedReason of the connection

const (
	UnknownReason          ClosedReason = "unknown"
	ConnectionTimedOut     ClosedReason = "timed out"
	ConnectionClosedByUser ClosedReason = "closed by end-user"
	ConnectionCanceled     ClosedReason = "canceled"
	ConnectionNetworkError ClosedReason = "network error"
	ConnectionSystemError  ClosedReason = "system error"
)

func (ClosedReason) String

func (r ClosedReason) String() string

String representation of the termination reason

type ComposedOf

type ComposedOf struct {
	// UserId of the session
	UserId string
	// HostId of the session
	HostId string
	// TargetId of the session
	TargetId string
	// HostSetId of the session
	HostSetId string
	// AuthTokenId of the session
	AuthTokenId string
	// ScopeId of the session
	ScopeId string
	// Endpoint. This is generated by the target, but is not stored in the
	// warehouse as the worker may need to e.g. resolve DNS. This is to round
	// trip the information to the worker when it validates a session.
	Endpoint string
	// Expiration time for the session
	ExpirationTime *timestamp.Timestamp
	// Max connections for the session
	ConnectionLimit int32
}

ComposedOf defines the boundary data that is referenced to compose a session.

func TestSessionParams

func TestSessionParams(t *testing.T, conn *gorm.DB, wrapper wrapping.Wrapper, iamRepo *iam.Repository) ComposedOf

TestSessionParams returns an initialized ComposedOf which can be used to create a session in the repository.

type ConnectWith

type ConnectWith struct {
	ConnectionId       string
	ClientTcpAddress   string
	ClientTcpPort      uint32
	EndpointTcpAddress string
	EndpointTcpPort    uint32
}

ConnectWith defines the boundary data that is saved in the repo when the worker has established a connection between the client and the endpoint.

type Connection

type Connection struct {
	// PublicId is used to access the connection via an API
	PublicId string `json:"public_id,omitempty" gorm:"primary_key"`
	// SessionId of the connection
	SessionId string `json:"session_id,omitempty" gorm:"default:null"`
	// ClientTcpAddress of the connection
	ClientTcpAddress string `json:"client_tcp_address,omitempty" gorm:"default:null"`
	// ClientTcpPort of the connection
	ClientTcpPort uint32 `json:"client_tcp_port,omitempty" gorm:"default:null"`
	// EndpointTcpAddress of the connection
	EndpointTcpAddress string `json:"endpoint_tcp_address,omitempty" gorm:"default:null"`
	// EndpointTcpPort of the connection
	EndpointTcpPort uint32 `json:"endpoint_tcp_port,omitempty" gorm:"default:null"`
	// BytesUp of the connection
	BytesUp uint64 `json:"bytes_up,omitempty" gorm:"default:null"`
	// BytesDown of the connection
	BytesDown uint64 `json:"bytes_down,omitempty" gorm:"default:null"`
	// ClosedReason of the conneciont
	ClosedReason string `json:"closed_reason,omitempty" gorm:"default:null"`
	// CreateTime from the RDBMS
	CreateTime *timestamp.Timestamp `json:"create_time,omitempty" gorm:"default:current_timestamp"`
	// UpdateTime from the RDBMS
	UpdateTime *timestamp.Timestamp `json:"update_time,omitempty" gorm:"default:current_timestamp"`
	// Version of the connection
	Version uint32 `json:"version,omitempty" gorm:"default:null"`
	// contains filtered or unexported fields
}

Connection contains information about session's connection to a target

func AllocConnection

func AllocConnection() Connection

AllocConnection will allocate a Session

func NewConnection

func NewConnection(sessionID, clientTcpAddress string, clientTcpPort uint32, endpointTcpAddr string, endpointTcpPort uint32, opt ...Option) (*Connection, error)

New creates a new in memory session. No options are currently supported.

func TestConnection

func TestConnection(t *testing.T, conn *gorm.DB, sessionId, clientTcpAddr string, clientTcpPort uint32, endpointTcpAddr string, endpointTcpPort uint32) *Connection

TestConnection creates a test connection for the sessionId in the repository.

func (*Connection) Clone

func (c *Connection) Clone() interface{}

Clone creates a clone of the Session

func (*Connection) GetPublicId

func (c *Connection) GetPublicId() string

func (*Connection) SetTableName

func (c *Connection) SetTableName(n string)

SetTableName sets the tablename and satisfies the ReplayableMessage interface. If the caller attempts to set the name to "" the name will be reset to the default name.

func (*Connection) TableName

func (c *Connection) TableName() string

TableName returns the tablename to override the default gorm table name

func (*Connection) VetForWrite

func (c *Connection) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error

VetForWrite implements db.VetForWrite() interface and validates the connection before it's written.

type ConnectionAuthzSummary

type ConnectionAuthzSummary struct {
	ExpirationTime         *timestamp.Timestamp
	ConnectionLimit        int32
	CurrentConnectionCount uint32
}

type ConnectionState

type ConnectionState struct {
	// ConnectionId is used to access the state via an API
	ConnectionId string `json:"public_id,omitempty" gorm:"primary_key"`
	// status of the connection
	Status ConnectionStatus `protobuf:"bytes,20,opt,name=status,proto3" json:"status,omitempty" gorm:"column:state"`
	// PreviousEndTime from the RDBMS
	PreviousEndTime *timestamp.Timestamp `json:"previous_end_time,omitempty" gorm:"default:current_timestamp"`
	// StartTime from the RDBMS
	StartTime *timestamp.Timestamp `json:"start_time,omitempty" gorm:"default:current_timestamp;primary_key"`
	// EndTime from the RDBMS
	EndTime *timestamp.Timestamp `json:"end_time,omitempty" gorm:"default:current_timestamp"`
	// contains filtered or unexported fields
}

ConnectionState of the state of the connection

func NewConnectionState

func NewConnectionState(connectionId string, state ConnectionStatus, opt ...Option) (*ConnectionState, error)

NewConnectionState creates a new in memory connection state. No options are currently supported.

func TestConnectionState

func TestConnectionState(t *testing.T, conn *gorm.DB, connectionId string, state ConnectionStatus) *ConnectionState

TestConnectionState creates a test connection state for the connectionId in the repository.

func (*ConnectionState) Clone

func (s *ConnectionState) Clone() interface{}

Clone creates a clone of the State

func (*ConnectionState) SetTableName

func (s *ConnectionState) SetTableName(n string)

SetTableName sets the tablename and satisfies the ReplayableMessage interface. If the caller attempts to set the name to "" the name will be reset to the default name.

func (*ConnectionState) TableName

func (s *ConnectionState) TableName() string

TableName returns the tablename to override the default gorm table name

func (*ConnectionState) VetForWrite

func (s *ConnectionState) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error

VetForWrite implements db.VetForWrite() interface and validates the state before it's written.

type ConnectionStatus

type ConnectionStatus string

ConnectionStatus of the connection's state

const (
	StatusAuthorized ConnectionStatus = "authorized"
	StatusConnected  ConnectionStatus = "connected"
	StatusClosed     ConnectionStatus = "closed"
)

func (ConnectionStatus) ProtoVal

ProtoVal returns the enum value corresponding to the state

func (ConnectionStatus) String

func (s ConnectionStatus) String() string

String representation of the state's status

type Option

type Option func(*options)

Option - how Options are passed as arguments

func WithExpirationTime

func WithExpirationTime(exp *timestamp.Timestamp) Option

WithExpirationTime allows specifying an expiration time for the session

func WithLimit

func WithLimit(limit int) Option

WithLimit provides an option to provide a limit. Intentionally allowing negative integers. If WithLimit < 0, then unlimited results are returned. If WithLimit == 0, then default limits are used for results.

func WithOrder

func WithOrder(order string) Option

WithOrder allows specifying an order for returned values

func WithScopeId

func WithScopeId(scopeId string) Option

WithScopeId allows specifying a scope ID criteria for the function.

func WithSessionIds

func WithSessionIds(ids ...string) Option

WithSessionIds allows the specification of the session ids to use for the operation.

func WithTestTofu

func WithTestTofu(tofu []byte) Option

WithTestTofu allows specifying a test tofu for a test session

func WithUserId

func WithUserId(userId string) Option

WithUserId allows specifying a user ID criteria for the function.

type Repository

type Repository struct {
	// contains filtered or unexported fields
}

Repository is the session database repository

func NewRepository

func NewRepository(r db.Reader, w db.Writer, kms *kms.Kms, opt ...Option) (*Repository, error)

NewRepository creates a new session Repository. Supports the options: WithLimit which sets a default limit on results returned by repo operations.

func (*Repository) ActivateSession

func (r *Repository) ActivateSession(ctx context.Context, sessionId string, sessionVersion uint32, serverId, serverType string, tofuToken []byte) (*Session, []*State, error)

ActivateSession will activate the session and is called by a worker after authenticating the session. The session must be in a "pending" state to be activated. States are ordered by start time descending. Returns an ErrSessionNotPending error if a connection cannot be made because the session was canceled or terminated.

func (*Repository) AuthorizeConnection

func (r *Repository) AuthorizeConnection(ctx context.Context, sessionId string) (*Connection, []*ConnectionState, *ConnectionAuthzSummary, error)

AuthorizeConnection will check to see if a connection is allowed. Currently, that authorization checks: * the hasn't expired based on the session.Expiration * number of connections already created is less than session.ConnectionLimit If authorization is success, it creates/stores a new connection in the repo and returns it, along with it's states. If the authorization fails, it an error of ErrInvalidStateForOperation.

func (*Repository) CancelSession

func (r *Repository) CancelSession(ctx context.Context, sessionId string, sessionVersion uint32) (*Session, error)

CancelSession sets a session's state to "canceling" in the repo. It's called when the user cancels a session and the controller wants to update the session state to "canceling" for the given reason, so the workers can get the "canceling signal" during their next status heartbeat. CancelSession is idempotent.

func (*Repository) CloseConnections

func (r *Repository) CloseConnections(ctx context.Context, closeWith []CloseWith, opt ...Option) ([]CloseConnectionResp, error)

CloseConnections set's a connection's state to "closed" in the repo. It's called by a worker after it's closed a connection between the client and the endpoint

func (*Repository) ConnectConnection

func (r *Repository) ConnectConnection(ctx context.Context, c ConnectWith) (*Connection, []*ConnectionState, error)

ConnectConnection updates a connection in the repo with a state of "connected".

func (*Repository) CreateSession

func (r *Repository) CreateSession(ctx context.Context, sessionWrapper wrapping.Wrapper, newSession *Session, opt ...Option) (*Session, ed25519.PrivateKey, error)

CreateSession inserts into the repository and returns the new Session with its State of "Pending". The following fields must be empty when creating a session: ServerId, ServerType, and PublicId. No options are currently supported.

func (*Repository) DeleteConnection

func (r *Repository) DeleteConnection(ctx context.Context, publicId string, opt ...Option) (int, error)

DeleteConnection will delete a connection from the repository.

func (*Repository) DeleteSession

func (r *Repository) DeleteSession(ctx context.Context, publicId string, opt ...Option) (int, error)

DeleteSession will delete a session from the repository.

func (*Repository) ListConnections

func (r *Repository) ListConnections(ctx context.Context, sessionId string, opt ...Option) ([]*Connection, error)

ListConnections will sessions. Supports the WithLimit and WithOrder options.

func (*Repository) ListSessions

func (r *Repository) ListSessions(ctx context.Context, opt ...Option) ([]*Session, error)

ListSessions will sessions. Supports the WithLimit, WithScopeId and WithSessionIds options.

func (*Repository) LookupConnection

func (r *Repository) LookupConnection(ctx context.Context, connectionId string, opt ...Option) (*Connection, []*ConnectionState, error)

LookupConnection will look up a connection in the repository and return the connection with its states. If the connection is not found, it will return nil, nil, nil. No options are currently supported.

func (*Repository) LookupSession

func (r *Repository) LookupSession(ctx context.Context, sessionId string, opt ...Option) (*Session, *ConnectionAuthzSummary, error)

LookupSession will look up a session in the repository and return the session with its states. Returned States are ordered by start time descending. If the session is not found, it will return nil, nil, nil. No options are currently supported.

func (*Repository) TerminateCompletedSessions

func (r *Repository) TerminateCompletedSessions(ctx context.Context) (int, error)

TerminateCompletedSessions will terminate sessions in the repo based on:

  • sessions that have exhausted their connection limit and all their connections are closed.
  • sessions that are expired and all their connections are closed.
  • sessions that are canceling and all their connections are closed

This function should called on a periodic basis a Controllers via it's "ticker" pattern.

func (*Repository) TerminateSession

func (r *Repository) TerminateSession(ctx context.Context, sessionId string, sessionVersion uint32, reason TerminationReason) (*Session, error)

TerminateSession sets a session's termination reason and it's state to "terminated" Sessions cannot be terminated which still have connections that are not closed.

type Session

type Session struct {
	// PublicId is used to access the session via an API
	PublicId string `json:"public_id,omitempty" gorm:"primary_key"`
	// UserId for the session
	UserId string `json:"user_id,omitempty" gorm:"default:null"`
	// HostId of the session
	HostId string `json:"host_id,omitempty" gorm:"default:null"`
	// ServerId that proxied the session
	ServerId string `json:"server_id,omitempty" gorm:"default:null"`
	// ServerType that proxied the session
	ServerType string `json:"server_type,omitempty" gorm:"default:null"`
	// TargetId for the session
	TargetId string `json:"target_id,omitempty" gorm:"default:null"`
	// HostSetId for the session
	HostSetId string `json:"host_set_id,omitempty" gorm:"default:null"`
	// AuthTokenId for the session
	AuthTokenId string `json:"auth_token_id,omitempty" gorm:"default:null"`
	// ScopeId for the session
	ScopeId string `json:"scope_id,omitempty" gorm:"default:null"`
	// Certificate to use when connecting (or if using custom certs, to
	// serve as the "login"). Raw DER bytes.  Private key is not, and should not be
	// stored in the database.
	Certificate []byte `json:"certificate,omitempty" gorm:"default:null"`
	// ExpirationTime - after this time the connection will be expired, e.g. forcefully terminated
	ExpirationTime *timestamp.Timestamp `json:"expiration_time,omitempty" gorm:"default:null"`
	// CtTofuToken is the ciphertext Tofutoken value stored in the database
	CtTofuToken []byte `json:"ct_tofu_token,omitempty" gorm:"column:tofu_token;default:null" wrapping:"ct,tofu_token"`
	// TofuToken - plain text of the "trust on first use" token for session
	TofuToken []byte `json:"tofu_token,omitempty" gorm:"-" wrapping:"pt,tofu_token"`
	// termination_reason for the session
	TerminationReason string `json:"termination_reason,omitempty" gorm:"default:null"`
	// CreateTime from the RDBMS
	CreateTime *timestamp.Timestamp `json:"create_time,omitempty" gorm:"default:current_timestamp"`
	// UpdateTime from the RDBMS
	UpdateTime *timestamp.Timestamp `json:"update_time,omitempty" gorm:"default:current_timestamp"`
	// Version for the session
	Version uint32 `json:"version,omitempty" gorm:"default:null"`
	// Endpoint
	Endpoint string `json:"-" gorm:"default:null"`
	// Maximum number of connections in a session
	ConnectionLimit int32 `json:"connection_limit,omitempty" gorm:"default:null"`

	// key_id is the key ID that was used for the encryption operation. It can be
	// used to identify a specific version of the key needed to decrypt the value,
	// which is useful for caching purposes.
	// @inject_tag: `gorm:"not_null"`
	KeyId string `json:"key_id,omitempty" gorm:"not_null"`

	// States for the session which are for read only and are ignored during
	// write operations
	States []*State `gorm:"-"`
	// contains filtered or unexported fields
}

Session contains information about a user's session with a target

func AllocSession

func AllocSession() Session

AllocSession will allocate a Session

func New

func New(c ComposedOf, opt ...Option) (*Session, error)

New creates a new in memory session.

func TestDefaultSession

func TestDefaultSession(t *testing.T, conn *gorm.DB, wrapper wrapping.Wrapper, iamRepo *iam.Repository, opt ...Option) *Session

TestDefaultSession creates a test session in the repository using defaults.

func TestSession

func TestSession(t *testing.T, conn *gorm.DB, wrapper wrapping.Wrapper, c ComposedOf, opt ...Option) *Session

TestSession creates a test session composed of c in the repository.

func (*Session) Clone

func (s *Session) Clone() interface{}

Clone creates a clone of the Session

func (*Session) GetPublicId

func (s *Session) GetPublicId() string

func (*Session) SetTableName

func (s *Session) SetTableName(n string)

SetTableName sets the tablename and satisfies the ReplayableMessage interface. If the caller attempts to set the name to "" the name will be reset to the default name.

func (*Session) TableName

func (s *Session) TableName() string

TableName returns the tablename to override the default gorm table name

func (*Session) VetForWrite

func (s *Session) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error

VetForWrite implements db.VetForWrite() interface and validates the session before it's written.

type State

type State struct {
	// SessionId references the session public id
	SessionId string `json:"session_id,omitempty" gorm:"primary_key"`
	// status of the session
	Status Status `json:"status,omitempty" gorm:"column:state"`
	// PreviousEndTime from the RDBMS
	PreviousEndTime *timestamp.Timestamp `json:"previous_end_time,omitempty" gorm:"default:current_timestamp"`
	// StartTime from the RDBMS
	StartTime *timestamp.Timestamp `json:"start_time,omitempty" gorm:"default:current_timestamp;primary_key"`
	// EndTime from the RDBMS
	EndTime *timestamp.Timestamp `json:"end_time,omitempty" gorm:"default:current_timestamp"`
	// contains filtered or unexported fields
}

State of the session

func NewState

func NewState(session_id string, state Status, opt ...Option) (*State, error)

NewState creates a new in memory session state. No options are currently supported.

func TestState

func TestState(t *testing.T, conn *gorm.DB, sessionId string, state Status) *State

TestState creates a test state for the sessionId in the repository.

func (*State) Clone

func (s *State) Clone() interface{}

Clone creates a clone of the State

func (*State) SetTableName

func (s *State) SetTableName(n string)

SetTableName sets the tablename and satisfies the ReplayableMessage interface. If the caller attempts to set the name to "" the name will be reset to the default name.

func (*State) TableName

func (s *State) TableName() string

TableName returns the tablename to override the default gorm table name

func (*State) VetForWrite

func (s *State) VetForWrite(ctx context.Context, r db.Reader, opType db.OpType, opt ...db.Option) error

VetForWrite implements db.VetForWrite() interface and validates the state before it's written.

type Status

type Status string

Status of the session's state

const (
	StatusPending    Status = "pending"
	StatusActive     Status = "active"
	StatusCanceling  Status = "canceling"
	StatusTerminated Status = "terminated"
)

func (Status) ProtoVal

func (s Status) ProtoVal() workerpbs.SESSIONSTATUS

ProtoVal returns the enum value corresponding to the state

func (Status) String

func (s Status) String() string

String representation of the state's status

type TerminationReason

type TerminationReason string

TerminationReason of the session

const (
	UnknownTermination TerminationReason = "unknown"
	TimedOut           TerminationReason = "timed out"
	ClosedByUser       TerminationReason = "closed by end-user"
	Terminated         TerminationReason = "terminated"
	NetworkError       TerminationReason = "network error"
	SystemError        TerminationReason = "system error"
	ConnectionLimit    TerminationReason = "connection limit"
	SessionCanceled    TerminationReason = "canceled"
)

func (TerminationReason) String

func (r TerminationReason) String() string

String representation of the termination reason

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL