diff --git a/internal/infrastructure/postgres/identities.go b/internal/infrastructure/postgres/identities.go index 98b8f3552..3741cf080 100644 --- a/internal/infrastructure/postgres/identities.go +++ b/internal/infrastructure/postgres/identities.go @@ -174,10 +174,8 @@ func (s *Store) Apply(ctx context.Context, id identity.IdentityID, expectedVersi now = time.Now().UTC() } next.UpdatedAt = now - if cur.Lifecycle == identity.LifecycleActive && next.Lifecycle != identity.LifecycleActive { - if err := keepActiveOwner(ctx, tx, string(id), ""); err != nil { - return identity.Identity{}, err - } + if err := guardLeavingActive(ctx, tx, id, cur.Lifecycle, next.Lifecycle); err != nil { + return identity.Identity{}, err } n, err := q.UpdateIdentity(ctx, postgresdb.UpdateIdentityParams{ @@ -190,11 +188,6 @@ func (s *Store) Apply(ctx context.Context, id identity.IdentityID, expectedVersi if n != 1 { return identity.Identity{}, identity.ErrConflict } - if next.Lifecycle != identity.LifecycleActive { - if _, err := tx.Exec(ctx, `DELETE FROM account_sessions WHERE identity_id=$1`, string(id)); err != nil { - return identity.Identity{}, err - } - } if command.Type == identity.CommandRename { if err := q.InsertIdentityAliasIgnoreConflict(ctx, postgresdb.InsertIdentityAliasIgnoreConflictParams{ Alias: next.DisplayName, IdentityID: string(id), @@ -211,6 +204,21 @@ func (s *Store) Apply(ctx context.Context, id identity.IdentityID, expectedVersi return next, nil } +// guardLeavingActive refuses suspending or retiring an org's last active +// owner, and signs out an identity that may no longer act. +func guardLeavingActive(ctx context.Context, tx pgx.Tx, id identity.IdentityID, from, to identity.Lifecycle) error { + if to == identity.LifecycleActive { + return nil + } + if from == identity.LifecycleActive { + if err := keepActiveOwner(ctx, tx, string(id), ""); err != nil { + return err + } + } + _, err := tx.Exec(ctx, `DELETE FROM account_sessions WHERE identity_id=$1`, string(id)) + return err +} + // ResolveSubject returns the identity bound to a provider subject. func (s *Store) ResolveSubject(ctx context.Context, subject identity.Subject) (identity.Identity, error) { i, err := s.queries().ResolveIdentitySubject(ctx, postgresdb.ResolveIdentitySubjectParams{