Update primary error functions to take a context, deprecate old functions (#1358)

* add new error funcs which take a ctx and deprecate existing funcs

* use context where available when writing error events

* remove circular internal/errors pkg dep

* suppress some chatty errors using errors.WithoutEvent()

* convert auth oidc funcs to take context where needed to write events

Co-authored-by: Jim <jlambert@hashicorp.com>
This commit is contained in:
s-christoffandJim authored and GitHub committed 2021-07-29 20:52:56 -04:00
1 parent 02ff2db66e
commit 6b78108ecf
227 files changed
+3945 -3736

No files matched your search

+14 -14
View File
@@ -64,7 +64,7 @@ func NewConnection(sessionID, clientTcpAddress string, clientTcpPort uint32, end
EndpointTcpPort: endpointTcpPort,
}
if err := c.validateNewConnection(); err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.WrapDeprecated(err, op)
}
return &c, nil
}
@@ -109,30 +109,30 @@ func (c *Connection) Clone() interface{} {
// VetForWrite implements db.VetForWrite() interface and validates the connection
// before it's written.
func (c *Connection) VetForWrite(_ context.Context, _ db.Reader, opType db.OpType, opt ...db.Option) error {
func (c *Connection) VetForWrite(ctx context.Context, _ db.Reader, opType db.OpType, opt ...db.Option) error {
const op = "session.(Connection).VetForWrite"
opts := db.GetOpts(opt...)
if c.PublicId == "" {
return errors.New(errors.InvalidParameter, op, "missing public id")
return errors.New(ctx, errors.InvalidParameter, op, "missing public id")
}
switch opType {
case db.CreateOp:
if err := c.validateNewConnection(); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
case db.UpdateOp:
switch {
case contains(opts.WithFieldMaskPaths, "PublicId"):
return errors.New(errors.InvalidParameter, op, "public id is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "public id is immutable")
case contains(opts.WithFieldMaskPaths, "SessionId"):
return errors.New(errors.InvalidParameter, op, "session id is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "session id is immutable")
case contains(opts.WithFieldMaskPaths, "CreateTime"):
return errors.New(errors.InvalidParameter, op, "create time is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "create time is immutable")
case contains(opts.WithFieldMaskPaths, "UpdateTime"):
return errors.New(errors.InvalidParameter, op, "update time is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "update time is immutable")
case contains(opts.WithFieldMaskPaths, "ClosedReason"):
if _, err := convertToClosedReason(c.ClosedReason); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
}
}
@@ -158,19 +158,19 @@ func (c *Connection) SetTableName(n string) {
func (c *Connection) validateNewConnection() error {
const op = "session.(Connection).validateNewConnection"
if c.SessionId == "" {
return errors.New(errors.InvalidParameter, op, "missing session id")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing session id")
}
if c.ClientTcpAddress == "" {
return errors.New(errors.InvalidParameter, op, "missing client address")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing client address")
}
if c.ClientTcpPort == 0 {
return errors.New(errors.InvalidParameter, op, "missing client port")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing client port")
}
if c.EndpointTcpAddress == "" {
return errors.New(errors.InvalidParameter, op, "missing endpoint address")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing endpoint address")
}
if c.EndpointTcpPort == 0 {
return errors.New(errors.InvalidParameter, op, "missing endpoint port")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing endpoint port")
}
return nil
}
+1 -1
View File
@@ -39,6 +39,6 @@ func convertToClosedReason(s string) (ClosedReason, error) {
case ConnectionSystemError.String():
return ConnectionSystemError, nil
default:
return "", errors.New(errors.InvalidParameter, op, fmt.Sprintf("%s is not a valid reason", s))
return "", errors.NewDeprecated(errors.InvalidParameter, op, fmt.Sprintf("%s is not a valid reason", s))
}
}
+2 -2
View File
@@ -16,10 +16,10 @@ type CloseWith struct {
func (c CloseWith) validate() error {
const op = "session.(CloseWith).validate"
if c.ConnectionId == "" {
return errors.New(errors.InvalidParameter, op, "missing connection id")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing connection id")
}
if c.ClosedReason.String() == "" {
return errors.New(errors.InvalidParameter, op, "missing closed reason")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing closed reason")
}
// 0 is valid for BytesUp and BytesDown
return nil
+8 -8
View File
@@ -87,7 +87,7 @@ func NewConnectionState(connectionId string, state ConnectionStatus, _ ...Option
Status: state,
}
if err := s.validate(); err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.WrapDeprecated(err, op)
}
return &s, nil
}
@@ -133,10 +133,10 @@ func (s *ConnectionState) Clone() interface{} {
// VetForWrite implements db.VetForWrite() interface and validates the state
// before it's written.
func (s *ConnectionState) VetForWrite(_ context.Context, _ db.Reader, _ db.OpType, _ ...db.Option) error {
func (s *ConnectionState) VetForWrite(ctx context.Context, _ db.Reader, _ db.OpType, _ ...db.Option) error {
const op = "session.(ConnectionState).VetForWrite"
if err := s.validate(); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -160,19 +160,19 @@ func (s *ConnectionState) SetTableName(n string) {
func (s *ConnectionState) validate() error {
const op = "session.(ConnectionState).validate"
if s.Status == "" {
return errors.New(errors.InvalidParameter, op, "missing status")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing status")
}
if s.ConnectionId == "" {
return errors.New(errors.InvalidParameter, op, "missing connection id")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing connection id")
}
if s.StartTime != nil {
return errors.New(errors.InvalidParameter, op, "start time is not settable")
return errors.NewDeprecated(errors.InvalidParameter, op, "start time is not settable")
}
if s.EndTime != nil {
return errors.New(errors.InvalidParameter, op, "end time is not settable")
return errors.NewDeprecated(errors.InvalidParameter, op, "end time is not settable")
}
if s.PreviousEndTime != nil {
return errors.New(errors.InvalidParameter, op, "previous end time is not settable")
return errors.NewDeprecated(errors.InvalidParameter, op, "previous end time is not settable")
}
return nil
}
+4 -4
View File
@@ -23,7 +23,7 @@ func newId() (string, error) {
const op = "session.newId"
id, err := db.NewPublicId(SessionPrefix)
if err != nil {
return "", errors.Wrap(err, op)
return "", errors.WrapDeprecated(err, op)
}
return id, nil
}
@@ -32,7 +32,7 @@ func newStateId() (string, error) {
const op = "session.newStateId"
id, err := db.NewPublicId(StatePrefix)
if err != nil {
return "", errors.Wrap(err, op)
return "", errors.WrapDeprecated(err, op)
}
return id, nil
}
@@ -41,7 +41,7 @@ func newConnectionId() (string, error) {
const op = "session.newConnectionId"
id, err := db.NewPublicId(ConnectionPrefix)
if err != nil {
return "", errors.Wrap(err, op)
return "", errors.WrapDeprecated(err, op)
}
return id, nil
}
@@ -50,7 +50,7 @@ func newConnectionStateId() (string, error) {
const op = "session.newConnectionStateId"
id, err := db.NewPublicId(ConnectionStatePrefix)
if err != nil {
return "", errors.Wrap(err, op)
return "", errors.WrapDeprecated(err, op)
}
return id, nil
}
+6 -6
View File
@@ -29,13 +29,13 @@ type Repository struct {
func NewRepository(r db.Reader, w db.Writer, kms *kms.Kms, opt ...Option) (*Repository, error) {
const op = "session.NewRepository"
if r == nil {
return nil, errors.New(errors.InvalidParameter, op, "nil reader")
return nil, errors.NewDeprecated(errors.InvalidParameter, op, "nil reader")
}
if w == nil {
return nil, errors.New(errors.InvalidParameter, op, "nil writer")
return nil, errors.NewDeprecated(errors.InvalidParameter, op, "nil writer")
}
if kms == nil {
return nil, errors.New(errors.InvalidParameter, op, "nil kms")
return nil, errors.NewDeprecated(errors.InvalidParameter, op, "nil kms")
}
opts := getOpts(opt...)
if opts.withLimit == 0 {
@@ -69,7 +69,7 @@ func (r *Repository) list(ctx context.Context, resources interface{}, where stri
dbOpts = append(dbOpts, db.WithOrder("create_time"))
}
if err := r.reader.SearchWhere(ctx, resources, where, args, dbOpts...); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -123,10 +123,10 @@ func (r *Repository) convertToSessions(ctx context.Context, sessionsWithState []
if len(workingSession.CtTofuToken) > 0 {
databaseWrapper, err := r.kms.GetWrapper(ctx, workingSession.ScopeId, kms.KeyPurposeDatabase)
if err != nil {
return nil, errors.Wrap(err, op, errors.WithMsg("unable to get database wrapper"))
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get database wrapper"))
}
if err := workingSession.decrypt(ctx, databaseWrapper); err != nil {
return nil, errors.Wrap(err, op, errors.WithMsg("cannot decrypt session value"))
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("cannot decrypt session value"))
}
} else {
workingSession.CtTofuToken = nil
+21 -21
View File
@@ -22,7 +22,7 @@ var DeadWorkerConnCloseMinGrace = int(servers.DefaultLiveness.Seconds())
func (r *Repository) LookupConnection(ctx context.Context, connectionId string, _ ...Option) (*Connection, []*ConnectionState, error) {
const op = "session.(Repository).LookupConnection"
if connectionId == "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing connectionId id")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing connectionId id")
}
connection := AllocConnection()
connection.PublicId = connectionId
@@ -33,11 +33,11 @@ func (r *Repository) LookupConnection(ctx context.Context, connectionId string,
db.ExpBackoff{},
func(read db.Reader, w db.Writer) error {
if err := read.LookupById(ctx, &connection); err != nil {
return errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("failed for %s", connectionId)))
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s", connectionId)))
}
var err error
if states, err = fetchConnectionStates(ctx, read, connectionId, db.WithOrder("start_time desc")); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
},
@@ -46,7 +46,7 @@ func (r *Repository) LookupConnection(ctx context.Context, connectionId string,
if errors.IsNotFoundError(err) {
return nil, nil, nil
}
return nil, nil, errors.Wrap(err, op)
return nil, nil, errors.Wrap(ctx, err, op)
}
return &connection, states, nil
}
@@ -56,12 +56,12 @@ func (r *Repository) LookupConnection(ctx context.Context, connectionId string,
func (r *Repository) ListConnectionsBySessionId(ctx context.Context, sessionId string, opt ...Option) ([]*Connection, error) {
const op = "session.(Repository).ListConnectionsBySessionId"
if sessionId == "" {
return nil, errors.New(errors.InvalidParameter, op, "no session ID supplied")
return nil, errors.New(ctx, errors.InvalidParameter, op, "no session ID supplied")
}
var connections []*Connection
err := r.list(ctx, &connections, "session_id = ?", []interface{}{sessionId}, opt...) // pass options, so WithLimit and WithOrder are supported
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
return connections, nil
}
@@ -70,12 +70,12 @@ func (r *Repository) ListConnectionsBySessionId(ctx context.Context, sessionId s
func (r *Repository) DeleteConnection(ctx context.Context, publicId string, _ ...Option) (int, error) {
const op = "session.(Repository).DeleteConnection"
if publicId == "" {
return db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing public id")
return db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing public id")
}
connection := AllocConnection()
connection.PublicId = publicId
if err := r.reader.LookupByPublicId(ctx, &connection); err != nil {
return db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("failed for %s", publicId)))
return db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s", publicId)))
}
var rowsDeleted int
@@ -91,17 +91,17 @@ func (r *Repository) DeleteConnection(ctx context.Context, publicId string, _ ..
deleteConnection,
)
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if rowsDeleted > 1 {
// return err, which will result in a rollback of the delete
return errors.New(errors.MultipleRecords, op, "more than 1 resource would have been deleted")
return errors.New(ctx, errors.MultipleRecords, op, "more than 1 resource would have been deleted")
}
return nil
},
)
if err != nil {
return db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("failed for %s", publicId)))
return db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s", publicId)))
}
return rowsDeleted, nil
}
@@ -117,7 +117,7 @@ func (r *Repository) DeleteConnection(ctx context.Context, publicId string, _ ..
func (r *Repository) CloseDeadConnectionsForWorker(ctx context.Context, serverId string, foundConns []string) (int, error) {
const op = "session.(Repository).CloseDeadConnectionsForWorker"
if serverId == "" {
return db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing server id")
return db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing server id")
}
args := make([]interface{}, 0, len(foundConns)+1)
@@ -142,13 +142,13 @@ func (r *Repository) CloseDeadConnectionsForWorker(ctx context.Context, serverId
var err error
rowsAffected, err = w.Exec(ctx, fmt.Sprintf(closeDeadConnectionsCte, publicIdStr), args)
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
},
)
if err != nil {
return db.NoRowsAffected, errors.Wrap(err, op)
return db.NoRowsAffected, errors.Wrap(ctx, err, op)
}
return rowsAffected, nil
}
@@ -168,7 +168,7 @@ type CloseConnectionsForDeadWorkersResult struct {
func (r *Repository) CloseConnectionsForDeadWorkers(ctx context.Context, gracePeriod int) ([]CloseConnectionsForDeadWorkersResult, error) {
const op = "session.(Repository).CloseConnectionsForDeadWorkers"
if gracePeriod < DeadWorkerConnCloseMinGrace {
return nil, errors.New(
return nil, errors.New(ctx,
errors.InvalidParameter, op, fmt.Sprintf("gracePeriod must be at least %d seconds", DeadWorkerConnCloseMinGrace))
}
@@ -180,14 +180,14 @@ func (r *Repository) CloseConnectionsForDeadWorkers(ctx context.Context, gracePe
func(reader db.Reader, w db.Writer) error {
rows, err := w.Query(ctx, closeConnectionsForDeadServersCte, []interface{}{gracePeriod})
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
defer rows.Close()
for rows.Next() {
var result CloseConnectionsForDeadWorkersResult
if err := w.ScanRows(rows, &result); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
results = append(results, result)
@@ -197,7 +197,7 @@ func (r *Repository) CloseConnectionsForDeadWorkers(ctx context.Context, gracePe
},
)
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
return results, nil
@@ -249,7 +249,7 @@ func (r *Repository) ShouldCloseConnectionsOnWorker(ctx context.Context, foundCo
args,
)
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
defer rows.Close()
@@ -257,7 +257,7 @@ func (r *Repository) ShouldCloseConnectionsOnWorker(ctx context.Context, foundCo
for rows.Next() {
var connectionId, sessionId string
if err := rows.Scan(&connectionId, &sessionId); err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
result[sessionId] = append(result[sessionId], connectionId)
@@ -270,7 +270,7 @@ func fetchConnectionStates(ctx context.Context, r db.Reader, connectionId string
const op = "session.fetchConnectionStates"
var states []*ConnectionState
if err := r.SearchWhere(ctx, &states, "connection_id = ?", []interface{}{connectionId}, opt...); err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
if len(states) == 0 {
return nil, nil
@@ -512,7 +512,7 @@ func TestRepository_CloseConnectionsForDeadWorkers(t *testing.T) {
{
// First, test the error/validation case.
result, err := repo.CloseConnectionsForDeadWorkers(ctx, 0)
require.Equal(err, errors.E(
require.Equal(err, errors.E(ctx,
errors.WithCode(errors.InvalidParameter),
errors.WithOp("session.(Repository).CloseConnectionsForDeadWorkers"),
errors.WithMsg(fmt.Sprintf("gracePeriod must be at least %d seconds", DeadWorkerConnCloseMinGrace)),
+106 -106
View File
@@ -23,56 +23,56 @@ import (
func (r *Repository) CreateSession(ctx context.Context, sessionWrapper wrapping.Wrapper, newSession *Session, _ ...Option) (*Session, ed25519.PrivateKey, error) {
const op = "session.(Repository).CreateSession"
if newSession == nil {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing session")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing session")
}
if newSession.PublicId != "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "public id is not empty")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "public id is not empty")
}
if len(newSession.Certificate) != 0 {
return nil, nil, errors.New(errors.InvalidParameter, op, "certificate is not empty")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "certificate is not empty")
}
if newSession.TargetId == "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing target id")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing target id")
}
if newSession.HostId == "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing host id")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing host id")
}
if newSession.UserId == "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing user id")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing user id")
}
if newSession.HostSetId == "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing host set id")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing host set id")
}
if newSession.AuthTokenId == "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing auth token id")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing auth token id")
}
if newSession.ScopeId == "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing scope id")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing scope id")
}
if newSession.ServerId != "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "server id is not empty")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "server id is not empty")
}
if newSession.ServerType != "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "server type is not empty")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "server type is not empty")
}
if newSession.CtTofuToken != nil {
return nil, nil, errors.New(errors.InvalidParameter, op, "ct is not empty")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "ct is not empty")
}
if newSession.TofuToken != nil {
return nil, nil, errors.New(errors.InvalidParameter, op, "tofu token is not empty")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "tofu token is not empty")
}
if newSession.ExpirationTime == nil || newSession.ExpirationTime.Timestamp.AsTime().IsZero() {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing expiration time")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing expiration time")
}
id, err := newId()
if err != nil {
return nil, nil, errors.Wrap(err, op)
return nil, nil, errors.Wrap(ctx, err, op)
}
privKey, certBytes, err := newCert(sessionWrapper, newSession.UserId, id, newSession.ExpirationTime.Timestamp.AsTime())
privKey, certBytes, err := newCert(ctx, sessionWrapper, newSession.UserId, id, newSession.ExpirationTime.Timestamp.AsTime())
if err != nil {
return nil, nil, errors.Wrap(err, op)
return nil, nil, errors.Wrap(ctx, err, op)
}
newSession.Certificate = certBytes
newSession.PublicId = id
@@ -87,36 +87,36 @@ func (r *Repository) CreateSession(ctx context.Context, sessionWrapper wrapping.
returnedSession = newSession.Clone().(*Session)
returnedSession.DynamicCredentials = nil
if err = w.Create(ctx, returnedSession); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
for _, cred := range newSession.DynamicCredentials {
cred.SessionId = newSession.PublicId
returnedCred := cred.clone()
if err = w.Create(ctx, returnedCred); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
returnedSession.DynamicCredentials = append(returnedSession.DynamicCredentials, returnedCred)
}
var foundStates []*State
// trigger will create new "Pending" state
if foundStates, err = fetchStates(ctx, read, returnedSession.PublicId); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if len(foundStates) != 1 {
return errors.New(errors.MultipleRecords, op, fmt.Sprintf("%d states found for new session %s", len(foundStates), returnedSession.PublicId))
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("%d states found for new session %s", len(foundStates), returnedSession.PublicId))
}
if len(foundStates) == 0 {
return errors.New(errors.SessionNotFound, op, fmt.Sprintf("no states found for new session %s", returnedSession.PublicId))
return errors.New(ctx, errors.SessionNotFound, op, fmt.Sprintf("no states found for new session %s", returnedSession.PublicId))
}
returnedSession.States = foundStates
if returnedSession.States[0].Status != StatusPending {
return errors.New(errors.InvalidSessionState, op, fmt.Sprintf("new session %s state is not valid: %s", returnedSession.PublicId, returnedSession.States[0].Status))
return errors.New(ctx, errors.InvalidSessionState, op, fmt.Sprintf("new session %s state is not valid: %s", returnedSession.PublicId, returnedSession.States[0].Status))
}
return nil
},
)
if err != nil {
return nil, nil, errors.Wrap(err, op)
return nil, nil, errors.Wrap(ctx, err, op)
}
return returnedSession, privKey, nil
}
@@ -128,7 +128,7 @@ func (r *Repository) CreateSession(ctx context.Context, sessionWrapper wrapping.
func (r *Repository) LookupSession(ctx context.Context, sessionId string, _ ...Option) (*Session, *ConnectionAuthzSummary, error) {
const op = "session.(Repository).LookupSession"
if sessionId == "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing session id")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing session id")
}
session := AllocSession()
session.PublicId = sessionId
@@ -138,17 +138,17 @@ func (r *Repository) LookupSession(ctx context.Context, sessionId string, _ ...O
db.ExpBackoff{},
func(read db.Reader, w db.Writer) error {
if err := read.LookupById(ctx, &session); err != nil {
return errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("failed for %s", sessionId)))
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s", sessionId)))
}
states, err := fetchStates(ctx, read, sessionId, db.WithOrder("start_time desc"))
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
session.States = states
var creds []*DynamicCredential
if err := read.SearchWhere(ctx, &creds, "session_id = ?", []interface{}{sessionId}); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if len(creds) > 0 {
session.DynamicCredentials = creds
@@ -160,15 +160,15 @@ func (r *Repository) LookupSession(ctx context.Context, sessionId string, _ ...O
if errors.IsNotFoundError(err) {
return nil, nil, nil
}
return nil, nil, errors.Wrap(err, op)
return nil, nil, errors.Wrap(ctx, err, op)
}
if len(session.CtTofuToken) > 0 {
databaseWrapper, err := r.kms.GetWrapper(ctx, session.ScopeId, kms.KeyPurposeDatabase)
if err != nil {
return nil, nil, errors.Wrap(err, op, errors.WithMsg("unable to get database wrapper"))
return nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to get database wrapper"))
}
if err := session.decrypt(ctx, databaseWrapper); err != nil {
return nil, nil, errors.Wrap(err, op, errors.WithMsg("cannot decrypt session value"))
return nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("cannot decrypt session value"))
}
} else {
session.CtTofuToken = nil
@@ -176,7 +176,7 @@ func (r *Repository) LookupSession(ctx context.Context, sessionId string, _ ...O
authzSummary, err := r.sessionAuthzSummary(ctx, sessionId)
if err != nil {
return nil, nil, errors.Wrap(err, op, errors.WithMsg("failed to get authz summary"))
return nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("failed to get authz summary"))
}
return &session, authzSummary, nil
@@ -248,7 +248,7 @@ func (r *Repository) ListSessions(ctx context.Context, opt ...Option) ([]*Sessio
rows, err := r.reader.Query(ctx, query, args)
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
defer rows.Close()
@@ -256,13 +256,13 @@ func (r *Repository) ListSessions(ctx context.Context, opt ...Option) ([]*Sessio
for rows.Next() {
var s sessionView
if err := r.reader.ScanRows(rows, &s); err != nil {
return nil, errors.Wrap(err, op, errors.WithMsg("scan row failed"))
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("scan row failed"))
}
sessionsWithState = append(sessionsWithState, &s)
}
sessions, err := r.convertToSessions(ctx, sessionsWithState, withListingConvert(true))
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
return sessions, nil
}
@@ -271,12 +271,12 @@ func (r *Repository) ListSessions(ctx context.Context, opt ...Option) ([]*Sessio
func (r *Repository) DeleteSession(ctx context.Context, publicId string, _ ...Option) (int, error) {
const op = "session.(Repository).DeleteSession"
if publicId == "" {
return db.NoRowsAffected, errors.New(errors.InvalidParameter, op, "missing public id")
return db.NoRowsAffected, errors.New(ctx, errors.InvalidParameter, op, "missing public id")
}
session := AllocSession()
session.PublicId = publicId
if err := r.reader.LookupByPublicId(ctx, &session); err != nil {
return db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("failed for %s", publicId)))
return db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s", publicId)))
}
var rowsDeleted int
@@ -292,17 +292,17 @@ func (r *Repository) DeleteSession(ctx context.Context, publicId string, _ ...Op
deleteSession,
)
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if rowsDeleted > 1 {
// return err, which will result in a rollback of the delete
return errors.New(errors.MultipleRecords, op, "more than 1 resource would have been deleted")
return errors.New(ctx, errors.MultipleRecords, op, "more than 1 resource would have been deleted")
}
return nil
},
)
if err != nil {
return db.NoRowsAffected, errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("failed for %s", publicId)))
return db.NoRowsAffected, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s", publicId)))
}
return rowsDeleted, nil
}
@@ -315,14 +315,14 @@ func (r *Repository) DeleteSession(ctx context.Context, publicId string, _ ...Op
func (r *Repository) CancelSession(ctx context.Context, sessionId string, sessionVersion uint32) (*Session, error) {
const op = "session.(Repository).CancelSession"
if sessionId == "" {
return nil, errors.New(errors.InvalidParameter, op, "missing session id")
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing session id")
}
if sessionVersion == 0 {
return nil, errors.New(errors.InvalidParameter, op, "missing session version")
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing session version")
}
s, ss, err := r.updateState(ctx, sessionId, sessionVersion, StatusCanceling)
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
s.States = ss
return s, nil
@@ -334,10 +334,10 @@ func (r *Repository) CancelSession(ctx context.Context, sessionId string, sessio
func (r *Repository) TerminateSession(ctx context.Context, sessionId string, sessionVersion uint32, reason TerminationReason) (*Session, error) {
const op = "session.(Repository).TerminateSession"
if sessionId == "" {
return nil, errors.New(errors.InvalidParameter, op, "missing session id")
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing session id")
}
if sessionVersion == 0 {
return nil, errors.New(errors.InvalidParameter, op, "missing session version")
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing session version")
}
updatedSession := AllocSession()
@@ -350,28 +350,28 @@ func (r *Repository) TerminateSession(ctx context.Context, sessionId string, ses
func(reader db.Reader, w db.Writer) error {
rowsAffected, err := w.Exec(ctx, terminateSessionCte, []interface{}{sessionId, sessionVersion})
if err != nil {
return errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("unable to terminate session %s", sessionId)))
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to terminate session %s", sessionId)))
}
if rowsAffected == 0 {
return errors.New(errors.InvalidSessionState, op, fmt.Sprintf("unable to terminate session %s", sessionId))
return errors.New(ctx, errors.InvalidSessionState, op, fmt.Sprintf("unable to terminate session %s", sessionId))
}
rowsUpdated, err := w.Update(ctx, &updatedSession, []string{"TerminationReason"}, nil, db.WithVersion(&sessionVersion))
if err != nil {
return errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("failed for %s", sessionId)))
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s", sessionId)))
}
if rowsUpdated != 1 {
return errors.New(errors.MultipleRecords, op, fmt.Sprintf("update to session %s would have updated %d session", updatedSession.PublicId, rowsUpdated))
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("update to session %s would have updated %d session", updatedSession.PublicId, rowsUpdated))
}
states, err := fetchStates(ctx, reader, sessionId, db.WithOrder("start_time desc"))
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
updatedSession.States = states
return nil
},
)
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
return &updatedSession, nil
}
@@ -393,13 +393,13 @@ func (r *Repository) TerminateCompletedSessions(ctx context.Context) (int, error
var err error
rowsAffected, err = w.Exec(ctx, termSessionsUpdate, nil)
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
},
)
if err != nil {
return db.NoRowsAffected, errors.Wrap(err, op)
return db.NoRowsAffected, errors.Wrap(ctx, err, op)
}
return rowsAffected, nil
}
@@ -414,11 +414,11 @@ func (r *Repository) TerminateCompletedSessions(ctx context.Context) (int, error
func (r *Repository) AuthorizeConnection(ctx context.Context, sessionId, workerId string) (*Connection, []*ConnectionState, *ConnectionAuthzSummary, error) {
const op = "session.(Repository).AuthorizeConnection"
if sessionId == "" {
return nil, nil, nil, errors.Wrap(status.Error(codes.FailedPrecondition, "missing session id"), op, errors.WithCode(errors.InvalidParameter))
return nil, nil, nil, errors.Wrap(ctx, status.Error(codes.FailedPrecondition, "missing session id"), op, errors.WithCode(errors.InvalidParameter))
}
connectionId, err := newConnectionId()
if err != nil {
return nil, nil, nil, errors.Wrap(err, op)
return nil, nil, nil, errors.Wrap(ctx, err, op)
}
connection := AllocConnection()
@@ -431,27 +431,27 @@ func (r *Repository) AuthorizeConnection(ctx context.Context, sessionId, workerI
func(reader db.Reader, w db.Writer) error {
rowsAffected, err := w.Exec(ctx, authorizeConnectionCte, []interface{}{sessionId, connectionId, workerId})
if err != nil {
return errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("unable to authorize connection %s", sessionId)))
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to authorize connection %s", sessionId)))
}
if rowsAffected == 0 {
return errors.Wrap(status.Errorf(codes.PermissionDenied, "session %s is not authorized (not active, expired or connection limit reached)", sessionId), op, errors.WithCode(errors.InvalidSessionState))
return errors.Wrap(ctx, status.Errorf(codes.PermissionDenied, "session %s is not authorized (not active, expired or connection limit reached)", sessionId), op, errors.WithCode(errors.InvalidSessionState))
}
if err := reader.LookupById(ctx, &connection); err != nil {
return errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("failed for session %s", sessionId)))
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for session %s", sessionId)))
}
connectionStates, err = fetchConnectionStates(ctx, reader, connectionId, db.WithOrder("start_time desc"))
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
},
)
if err != nil {
return nil, nil, nil, errors.Wrap(err, op)
return nil, nil, nil, errors.Wrap(ctx, err, op)
}
authzSummary, err := r.sessionAuthzSummary(ctx, connection.SessionId)
if err != nil {
return nil, nil, nil, errors.Wrap(err, op)
return nil, nil, nil, errors.Wrap(ctx, err, op)
}
return &connection, connectionStates, authzSummary, nil
}
@@ -466,18 +466,18 @@ func (r *Repository) sessionAuthzSummary(ctx context.Context, sessionId string)
const op = "session.(Repository).sessionAuthzSummary"
rows, err := r.reader.Query(ctx, remainingConnectionsCte, []interface{}{sessionId})
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
defer rows.Close()
var info *ConnectionAuthzSummary
for rows.Next() {
if info != nil {
return nil, errors.New(errors.MultipleRecords, op, "query returned more than one row")
return nil, errors.New(ctx, errors.MultipleRecords, op, "query returned more than one row")
}
info = &ConnectionAuthzSummary{}
if err := r.reader.ScanRows(rows, info); err != nil {
return nil, errors.Wrap(err, op, errors.WithMsg("scan row failed"))
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("scan row failed"))
}
}
return info, nil
@@ -488,7 +488,7 @@ func (r *Repository) ConnectConnection(ctx context.Context, c ConnectWith) (*Con
const op = "session.(Repository).ConnectConnection"
// ConnectWith.validate will check all the fields...
if err := c.validate(); err != nil {
return nil, nil, errors.Wrap(err, op)
return nil, nil, errors.Wrap(ctx, err, op)
}
var connection Connection
var connectionStates []*ConnectionState
@@ -511,28 +511,28 @@ func (r *Repository) ConnectConnection(ctx context.Context, c ConnectWith) (*Con
}
rowsUpdated, err := w.Update(ctx, &connection, fieldMask, nil)
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if err == nil && rowsUpdated > 1 {
// return err, which will result in a rollback of the update
return errors.New(errors.MultipleRecords, op, "more than 1 resource would have been updated")
return errors.New(ctx, errors.MultipleRecords, op, "more than 1 resource would have been updated")
}
newState, err := NewConnectionState(connection.PublicId, StatusConnected)
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if err := w.Create(ctx, newState); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
connectionStates, err = fetchConnectionStates(ctx, reader, c.ConnectionId, db.WithOrder("start_time desc"))
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
},
)
if err != nil {
return nil, nil, errors.Wrap(err, op)
return nil, nil, errors.Wrap(ctx, err, op)
}
return &connection, connectionStates, nil
}
@@ -550,11 +550,11 @@ type CloseConnectionResp struct {
func (r *Repository) CloseConnections(ctx context.Context, closeWith []CloseWith, _ ...Option) ([]CloseConnectionResp, error) {
const op = "session.(Repository).CloseConnections"
if len(closeWith) == 0 {
return nil, errors.New(errors.InvalidParameter, op, "missing connections")
return nil, errors.New(ctx, errors.InvalidParameter, op, "missing connections")
}
for _, cw := range closeWith {
if err := cw.validate(); err != nil {
return nil, errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("%s was invalid", cw.ConnectionId)))
return nil, errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("%s was invalid", cw.ConnectionId)))
}
}
var resp []CloseConnectionResp
@@ -578,14 +578,14 @@ func (r *Repository) CloseConnections(ctx context.Context, closeWith []CloseWith
nil,
)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("unable to update connection %s", cw.ConnectionId)))
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to update connection %s", cw.ConnectionId)))
}
if rowsUpdated != 1 {
return errors.New(errors.MultipleRecords, op, fmt.Sprintf("%d would have been updated for connection %s", rowsUpdated, cw.ConnectionId))
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("%d would have been updated for connection %s", rowsUpdated, cw.ConnectionId))
}
states, err := fetchConnectionStates(ctx, reader, cw.ConnectionId, db.WithOrder("start_time desc"))
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
resp = append(resp, CloseConnectionResp{
Connection: &updateConnection,
@@ -597,7 +597,7 @@ func (r *Repository) CloseConnections(ctx context.Context, closeWith []CloseWith
},
)
if err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
return resp, nil
}
@@ -610,19 +610,19 @@ func (r *Repository) CloseConnections(ctx context.Context, closeWith []CloseWith
func (r *Repository) ActivateSession(ctx context.Context, sessionId string, sessionVersion uint32, serverId, serverType string, tofuToken []byte) (*Session, []*State, error) {
const op = "session.(Repository).ActivateSession"
if sessionId == "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing session id")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing session id")
}
if sessionVersion == 0 {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing version")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing version")
}
if serverId == "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing server id")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing server id")
}
if serverType == "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing server type")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing server type")
}
if len(tofuToken) == 0 {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing tofu token")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing tofu token")
}
updatedSession := AllocSession()
@@ -635,48 +635,48 @@ func (r *Repository) ActivateSession(ctx context.Context, sessionId string, sess
func(reader db.Reader, w db.Writer) error {
rowsAffected, err := w.Exec(ctx, activateStateCte, []interface{}{sessionId, sessionVersion})
if err != nil {
return errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("unable to activate session %s", sessionId)))
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to activate session %s", sessionId)))
}
if rowsAffected == 0 {
return errors.New(errors.InvalidSessionState, op, "session is not in a pending state")
return errors.New(ctx, errors.InvalidSessionState, op, "session is not in a pending state")
}
foundSession := AllocSession()
foundSession.PublicId = sessionId
if err := reader.LookupById(ctx, &foundSession); err != nil {
return errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("failed for %s", sessionId)))
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("failed for %s", sessionId)))
}
databaseWrapper, err := r.kms.GetWrapper(ctx, foundSession.ScopeId, kms.KeyPurposeDatabase)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to get database wrapper"))
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get database wrapper"))
}
if len(foundSession.TofuToken) > 0 && subtle.ConstantTimeCompare(foundSession.TofuToken, tofuToken) != 1 {
return errors.New(errors.TokenMismatch, op, "tofu token mismatch")
return errors.New(ctx, errors.TokenMismatch, op, "tofu token mismatch")
}
updatedSession.TofuToken = tofuToken
updatedSession.ServerId = serverId
updatedSession.ServerType = serverType
if err := updatedSession.encrypt(ctx, databaseWrapper); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
rowsUpdated, err := w.Update(ctx, &updatedSession, []string{"CtTofuToken"}, nil)
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if err == nil && rowsUpdated > 1 {
// return err, which will result in a rollback of the update
return errors.New(errors.MultipleRecords, op, "more than 1 resource would have been updated")
return errors.New(ctx, errors.MultipleRecords, op, "more than 1 resource would have been updated")
}
returnedStates, err = fetchStates(ctx, reader, sessionId, db.WithOrder("start_time desc"))
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
},
)
if err != nil {
return nil, nil, errors.Wrap(err, op)
return nil, nil, errors.Wrap(ctx, err, op)
}
return &updatedSession, returnedStates, nil
}
@@ -687,16 +687,16 @@ func (r *Repository) ActivateSession(ctx context.Context, sessionId string, sess
func (r *Repository) updateState(ctx context.Context, sessionId string, sessionVersion uint32, s Status, _ ...Option) (*Session, []*State, error) {
const op = "session.(Repository).updateState"
if sessionId == "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing session id")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing session id")
}
if sessionVersion == 0 {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing version")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing version")
}
if s == "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing session status")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing session status")
}
if s == StatusActive {
return nil, nil, errors.New(errors.InvalidParameter, op, "you must call ActivateSession to update a session's state to active")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "you must call ActivateSession to update a session's state to active")
}
var rowsAffected int
@@ -713,18 +713,18 @@ func (r *Repository) updateState(ctx context.Context, sessionId string, sessionV
updatedSession.Version = uint32(sessionVersion) + 1
rowsUpdated, err := w.Update(ctx, &updatedSession, []string{"Version"}, nil, db.WithVersion(&sessionVersion))
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if rowsUpdated != 1 {
return errors.New(errors.MultipleRecords, op, fmt.Sprintf("updated session and %d rows updated", rowsUpdated))
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("updated session and %d rows updated", rowsUpdated))
}
if len(updatedSession.CtTofuToken) > 0 {
databaseWrapper, err := r.kms.GetWrapper(ctx, updatedSession.ScopeId, kms.KeyPurposeDatabase)
if err != nil {
return errors.Wrap(err, op, errors.WithMsg("unable to get database wrapper"))
return errors.Wrap(ctx, err, op, errors.WithMsg("unable to get database wrapper"))
}
if err := updatedSession.decrypt(ctx, databaseWrapper); err != nil {
return errors.Wrap(err, op, errors.WithMsg("cannot decrypt session value"))
return errors.Wrap(ctx, err, op, errors.WithMsg("cannot decrypt session value"))
}
} else {
updatedSession.CtTofuToken = nil
@@ -732,23 +732,23 @@ func (r *Repository) updateState(ctx context.Context, sessionId string, sessionV
rowsAffected, err = w.Exec(ctx, updateSessionState, []interface{}{sessionId, s.String()})
if err != nil {
return errors.Wrap(err, op, errors.WithMsg(fmt.Sprintf("unable to update session %s state to %s", sessionId, s.String())))
return errors.Wrap(ctx, err, op, errors.WithMsg(fmt.Sprintf("unable to update session %s state to %s", sessionId, s.String())))
}
if rowsAffected != 0 && rowsAffected != 1 {
return errors.New(errors.MultipleRecords, op, fmt.Sprintf("updated session %s to state %s and %d rows inserted (should be 0 or 1)", sessionId, s.String(), rowsAffected))
return errors.New(ctx, errors.MultipleRecords, op, fmt.Sprintf("updated session %s to state %s and %d rows inserted (should be 0 or 1)", sessionId, s.String(), rowsAffected))
}
returnedStates, err = fetchStates(ctx, reader, sessionId, db.WithOrder("start_time desc"))
if err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if len(returnedStates) < 1 && returnedStates[0].Status != s {
return errors.New(errors.InvalidSessionState, op, fmt.Sprintf("failed to update %s to a state of %s", sessionId, s.String()))
return errors.New(ctx, errors.InvalidSessionState, op, fmt.Sprintf("failed to update %s to a state of %s", sessionId, s.String()))
}
return nil
},
)
if err != nil {
return nil, nil, errors.Wrap(err, op, errors.WithMsg("error creating new state"))
return nil, nil, errors.Wrap(ctx, err, op, errors.WithMsg("error creating new state"))
}
return &updatedSession, returnedStates, nil
}
@@ -757,7 +757,7 @@ func fetchStates(ctx context.Context, r db.Reader, sessionId string, opt ...db.O
const op = "session.fetchStates"
var states []*State
if err := r.SearchWhere(ctx, &states, "session_id = ?", []interface{}{sessionId}, opt...); err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.Wrap(ctx, err, op)
}
if len(states) == 0 {
return nil, nil
+41 -41
View File
@@ -141,7 +141,7 @@ func New(c ComposedOf, _ ...Option) (*Session, error) {
DynamicCredentials: c.DynamicCredentials,
}
if err := s.validateNewSession(); err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.WrapDeprecated(err, op)
}
return &s, nil
}
@@ -225,53 +225,53 @@ func (s *Session) Clone() interface{} {
// VetForWrite implements db.VetForWrite() interface and validates the session
// before it's written.
func (s *Session) VetForWrite(_ context.Context, _ db.Reader, opType db.OpType, opt ...db.Option) error {
func (s *Session) VetForWrite(ctx context.Context, _ db.Reader, opType db.OpType, opt ...db.Option) error {
const op = "session.(Session).VetForWrite"
opts := db.GetOpts(opt...)
if s.PublicId == "" {
return errors.New(errors.InvalidParameter, op, "missing public id")
return errors.New(ctx, errors.InvalidParameter, op, "missing public id")
}
switch opType {
case db.CreateOp:
if err := s.validateNewSession(); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
if len(s.Certificate) == 0 {
return errors.New(errors.InvalidParameter, op, "missing certificate")
return errors.New(ctx, errors.InvalidParameter, op, "missing certificate")
}
case db.UpdateOp:
switch {
case contains(opts.WithFieldMaskPaths, "PublicId"):
return errors.New(errors.InvalidParameter, op, "public id is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "public id is immutable")
case contains(opts.WithFieldMaskPaths, "UserId"):
return errors.New(errors.InvalidParameter, op, "user id is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "user id is immutable")
case contains(opts.WithFieldMaskPaths, "HostId"):
return errors.New(errors.InvalidParameter, op, "host id is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "host id is immutable")
case contains(opts.WithFieldMaskPaths, "TargetId"):
return errors.New(errors.InvalidParameter, op, "target id is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "target id is immutable")
case contains(opts.WithFieldMaskPaths, "HostSetId"):
return errors.New(errors.InvalidParameter, op, "host set id is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "host set id is immutable")
case contains(opts.WithFieldMaskPaths, "AuthTokenId"):
return errors.New(errors.InvalidParameter, op, "auth token id is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "auth token id is immutable")
case contains(opts.WithFieldMaskPaths, "Certificate"):
return errors.New(errors.InvalidParameter, op, "certificate is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "certificate is immutable")
case contains(opts.WithFieldMaskPaths, "CreateTime"):
return errors.New(errors.InvalidParameter, op, "create time is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "create time is immutable")
case contains(opts.WithFieldMaskPaths, "UpdateTime"):
return errors.New(errors.InvalidParameter, op, "update time is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "update time is immutable")
case contains(opts.WithFieldMaskPaths, "Endpoint"):
return errors.New(errors.InvalidParameter, op, "endpoint is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "endpoint is immutable")
case contains(opts.WithFieldMaskPaths, "ExpirationTime"):
return errors.New(errors.InvalidParameter, op, "expiration time is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "expiration time is immutable")
case contains(opts.WithFieldMaskPaths, "ConnectionLimit"):
return errors.New(errors.InvalidParameter, op, "connection limit is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "connection limit is immutable")
case contains(opts.WithFieldMaskPaths, "WorkerFilter"):
return errors.New(errors.InvalidParameter, op, "worker filter is immutable")
return errors.New(ctx, errors.InvalidParameter, op, "worker filter is immutable")
case contains(opts.WithFieldMaskPaths, "DynamicCredentials"):
return errors.New(errors.InvalidParameter, op, "dynamic credentials are immutable")
return errors.New(ctx, errors.InvalidParameter, op, "dynamic credentials are immutable")
case contains(opts.WithFieldMaskPaths, "TerminationReason"):
if _, err := convertToReason(s.TerminationReason); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
}
}
@@ -297,43 +297,43 @@ func (s *Session) SetTableName(n string) {
func (s *Session) validateNewSession() error {
const op = "session.(Session).validateNewSession"
if s.UserId == "" {
return errors.New(errors.InvalidParameter, op, "missing user id")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing user id")
}
if s.HostId == "" {
return errors.New(errors.InvalidParameter, op, "missing host id")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing host id")
}
if s.TargetId == "" {
return errors.New(errors.InvalidParameter, op, "missing target id")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing target id")
}
if s.HostSetId == "" {
return errors.New(errors.InvalidParameter, op, "missing host set id")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing host set id")
}
if s.AuthTokenId == "" {
return errors.New(errors.InvalidParameter, op, "missing auth token id")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing auth token id")
}
if s.ScopeId == "" {
return errors.New(errors.InvalidParameter, op, "missing scope id")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing scope id")
}
if s.Endpoint == "" {
return errors.New(errors.InvalidParameter, op, "missing endpoint")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing endpoint")
}
if s.ExpirationTime.GetTimestamp().AsTime().IsZero() {
return errors.New(errors.InvalidParameter, op, "missing expiration time")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing expiration time")
}
if s.TerminationReason != "" {
return errors.New(errors.InvalidParameter, op, "termination reason must be empty")
return errors.NewDeprecated(errors.InvalidParameter, op, "termination reason must be empty")
}
if s.ServerId != "" {
return errors.New(errors.InvalidParameter, op, "server id must be empty")
return errors.NewDeprecated(errors.InvalidParameter, op, "server id must be empty")
}
if s.ServerType != "" {
return errors.New(errors.InvalidParameter, op, "server type must be empty")
return errors.NewDeprecated(errors.InvalidParameter, op, "server type must be empty")
}
if s.TofuToken != nil {
return errors.New(errors.InvalidParameter, op, "tofu token must be empty")
return errors.NewDeprecated(errors.InvalidParameter, op, "tofu token must be empty")
}
if s.CtTofuToken != nil {
return errors.New(errors.InvalidParameter, op, "ct must be empty")
return errors.NewDeprecated(errors.InvalidParameter, op, "ct must be empty")
}
// It is okay for the worker filter to be empty, so it is not checked here.
return nil
@@ -348,20 +348,20 @@ func contains(ss []string, t string) bool {
return false
}
func newCert(wrapper wrapping.Wrapper, userId, jobId string, exp time.Time) (ed25519.PrivateKey, []byte, error) {
func newCert(ctx context.Context, wrapper wrapping.Wrapper, userId, jobId string, exp time.Time) (ed25519.PrivateKey, []byte, error) {
const op = "session.newCert"
if wrapper == nil {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing wrapper")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing wrapper")
}
if userId == "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing user id")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing user id")
}
if jobId == "" {
return nil, nil, errors.New(errors.InvalidParameter, op, "missing job id")
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing job id")
}
pubKey, privKey, err := DeriveED25519Key(wrapper, userId, jobId)
if err != nil {
return nil, nil, errors.Wrap(err, op)
return nil, nil, errors.Wrap(ctx, err, op)
}
template := &x509.Certificate{
ExtKeyUsage: []x509.ExtKeyUsage{
@@ -379,7 +379,7 @@ func newCert(wrapper wrapping.Wrapper, userId, jobId string, exp time.Time) (ed2
certBytes, err := x509.CreateCertificate(rand.Reader, template, template, pubKey, privKey)
if err != nil {
return nil, nil, errors.Wrap(err, op, errors.WithCode(errors.GenCert))
return nil, nil, errors.Wrap(ctx, err, op, errors.WithCode(errors.GenCert))
}
return privKey, certBytes, nil
}
@@ -387,7 +387,7 @@ func newCert(wrapper wrapping.Wrapper, userId, jobId string, exp time.Time) (ed2
func (s *Session) encrypt(ctx context.Context, cipher wrapping.Wrapper) error {
const op = "session.(Session).encrypt"
if err := structwrapping.WrapStruct(ctx, cipher, s, nil); err != nil {
return errors.Wrap(err, op, errors.WithCode(errors.Encrypt))
return errors.Wrap(ctx, err, op, errors.WithCode(errors.Encrypt))
}
s.KeyId = cipher.KeyID()
return nil
@@ -396,7 +396,7 @@ func (s *Session) encrypt(ctx context.Context, cipher wrapping.Wrapper) error {
func (s *Session) decrypt(ctx context.Context, cipher wrapping.Wrapper) error {
const op = "session.(Session).decrypt"
if err := structwrapping.UnwrapStruct(ctx, cipher, s, nil); err != nil {
return errors.Wrap(err, op, errors.WithCode(errors.Decrypt))
return errors.Wrap(ctx, err, op, errors.WithCode(errors.Decrypt))
}
return nil
}
+5 -5
View File
@@ -17,19 +17,19 @@ type ConnectWith struct {
func (c ConnectWith) validate() error {
const op = "session.(ConnectWith).validate"
if c.ConnectionId == "" {
return errors.New(errors.InvalidParameter, op, "missing session id")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing session id")
}
if c.ClientTcpAddress == "" {
return errors.New(errors.InvalidParameter, op, "missing client tcp address")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing client tcp address")
}
if c.ClientTcpPort == 0 {
return errors.New(errors.InvalidParameter, op, "missing client ctp port")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing client ctp port")
}
if c.EndpointTcpAddress == "" {
return errors.New(errors.InvalidParameter, op, "missing endpoint tcp address")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing endpoint tcp address")
}
if c.EndpointTcpPort == 0 {
return errors.New(errors.InvalidParameter, op, "missing endpoint ctp port")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing endpoint ctp port")
}
return nil
}
+3 -2
View File
@@ -131,6 +131,7 @@ func TestSession_Create(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
assert, require := assert.New(t), require.New(t)
got, err := New(tt.args.composedOf)
if tt.wantErr {
@@ -144,10 +145,10 @@ func TestSession_Create(t *testing.T) {
id, err := db.NewPublicId(SessionPrefix)
require.NoError(err)
got.PublicId = id
_, certBytes, err := newCert(wrapper, got.UserId, id, composedOf.ExpirationTime.Timestamp.AsTime())
_, certBytes, err := newCert(ctx, wrapper, got.UserId, id, composedOf.ExpirationTime.Timestamp.AsTime())
require.NoError(err)
got.Certificate = certBytes
err = db.New(conn).Create(context.Background(), got)
err = db.New(conn).Create(ctx, got)
if tt.wantCreateErr {
assert.Error(err)
return
+8 -8
View File
@@ -76,7 +76,7 @@ func NewState(session_id string, state Status, _ ...Option) (*State, error) {
}
if err := s.validate(); err != nil {
return nil, errors.Wrap(err, op)
return nil, errors.WrapDeprecated(err, op)
}
return &s, nil
}
@@ -122,10 +122,10 @@ func (s *State) Clone() interface{} {
// VetForWrite implements db.VetForWrite() interface and validates the state
// before it's written.
func (s *State) VetForWrite(_ context.Context, _ db.Reader, _ db.OpType, _ ...db.Option) error {
func (s *State) VetForWrite(ctx context.Context, _ db.Reader, _ db.OpType, _ ...db.Option) error {
const op = "session.(State).VetForWrite"
if err := s.validate(); err != nil {
return errors.Wrap(err, op)
return errors.Wrap(ctx, err, op)
}
return nil
}
@@ -149,19 +149,19 @@ func (s *State) SetTableName(n string) {
func (s *State) validate() error {
const op = "session.(State).validate"
if s.Status == "" {
return errors.New(errors.InvalidParameter, op, "missing status")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing status")
}
if s.SessionId == "" {
return errors.New(errors.InvalidParameter, op, "missing session id")
return errors.NewDeprecated(errors.InvalidParameter, op, "missing session id")
}
if s.StartTime != nil {
return errors.New(errors.InvalidParameter, op, "start time is not settable")
return errors.NewDeprecated(errors.InvalidParameter, op, "start time is not settable")
}
if s.EndTime != nil {
return errors.New(errors.InvalidParameter, op, "end time is not settable")
return errors.NewDeprecated(errors.InvalidParameter, op, "end time is not settable")
}
if s.PreviousEndTime != nil {
return errors.New(errors.InvalidParameter, op, "previous end time is not settable")
return errors.NewDeprecated(errors.InvalidParameter, op, "previous end time is not settable")
}
return nil
}
+1 -1
View File
@@ -43,6 +43,6 @@ func convertToReason(s string) (TerminationReason, error) {
case ConnectionLimit.String():
return ConnectionLimit, nil
default:
return "", errors.New(errors.InvalidParameter, op, fmt.Sprintf("%s is not a valid reason", s))
return "", errors.NewDeprecated(errors.InvalidParameter, op, fmt.Sprintf("%s is not a valid reason", s))
}
}
+7 -6
View File
@@ -71,6 +71,7 @@ func TestState(t *testing.T, conn *gorm.DB, sessionId string, state Status) *Sta
// are passed into New, and withServerId is handled locally.
func TestSession(t *testing.T, conn *gorm.DB, wrapper wrapping.Wrapper, c ComposedOf, opt ...Option) *Session {
t.Helper()
ctx := context.Background()
opts := getOpts(opt...)
require := require.New(t)
if c.ExpirationTime == nil {
@@ -83,25 +84,25 @@ func TestSession(t *testing.T, conn *gorm.DB, wrapper wrapping.Wrapper, c Compos
id, err := newId()
require.NoError(err)
s.PublicId = id
_, certBytes, err := newCert(wrapper, c.UserId, id, c.ExpirationTime.Timestamp.AsTime())
_, certBytes, err := newCert(ctx, wrapper, c.UserId, id, c.ExpirationTime.Timestamp.AsTime())
require.NoError(err)
s.Certificate = certBytes
s.ServerId = opts.withServerId
if len(s.TofuToken) != 0 {
err = s.encrypt(context.Background(), wrapper)
err = s.encrypt(ctx, wrapper)
}
require.NoError(err)
err = rw.Create(context.Background(), s, opts.withDbOpts...)
err = rw.Create(ctx, s, opts.withDbOpts...)
require.NoError(err)
for _, cred := range s.DynamicCredentials {
cred.SessionId = s.PublicId
err := rw.Create(context.Background(), cred)
err := rw.Create(ctx, cred)
require.NoError(err)
}
ss, err := fetchStates(context.Background(), rw, s.PublicId, append(opts.withDbOpts, db.WithOrder("start_time desc"))...)
ss, err := fetchStates(ctx, rw, s.PublicId, append(opts.withDbOpts, db.WithOrder("start_time desc"))...)
require.NoError(err)
s.States = ss
@@ -204,5 +205,5 @@ func TestWorker(t *testing.T, conn *gorm.DB, wrapper wrapping.Wrapper, opt ...Op
// as a parameter. It's currently used in controller.jobTestingHandler() and
// should be deprecated once that function is refactored to use sessions properly.
func TestCert(wrapper wrapping.Wrapper, userId, jobId string) (ed25519.PrivateKey, []byte, error) {
return newCert(wrapper, userId, jobId, time.Now().Add(5*time.Minute))
return newCert(context.Background(), wrapper, userId, jobId, time.Now().Add(5*time.Minute))
}
+1 -1
View File
@@ -22,7 +22,7 @@ func DeriveED25519Key(wrapper wrapping.Wrapper, userId, jobId string) (ed25519.P
reader, err := kms.NewDerivedReader(wrapper, 32, uId, jId)
if err != nil {
return nil, nil, errors.Wrap(err, op)
return nil, nil, errors.WrapDeprecated(err, op)
}
return ed25519.GenerateKey(reader)
}