From c99e09d665427bdccc8de4d5ba957e7a5ee2fe53 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 17 Oct 2026 10:07:45 +1100 Subject: [PATCH] fix(postgres): keep every organisation an active owner --- internal/domain/org/org.go | 1 + .../infrastructure/postgres/identities.go | 5 ++ internal/infrastructure/postgres/orgs.go | 16 ++++- .../infrastructure/postgres/owners_guard.go | 64 +++++++++++++++++++ .../infrastructure/staterpc/identities.go | 6 ++ internal/infrastructure/staterpc/values.go | 1 + internal/webui/api_identities.go | 3 +- internal/webui/api_orgs.go | 3 +- 8 files changed, 95 insertions(+), 4 deletions(-) create mode 100644 internal/infrastructure/postgres/owners_guard.go diff --git a/internal/domain/org/org.go b/internal/domain/org/org.go index 627c986a4..b4e3b38f6 100644 --- a/internal/domain/org/org.go +++ b/internal/domain/org/org.go @@ -33,6 +33,7 @@ var ( ErrOrgExists = errors.New("org: org already exists") ErrWorkspaceExists = errors.New("org: workspace already exists") ErrMembershipExists = errors.New("org: membership already exists") + ErrLastOwner = errors.New("org: this is the organisation's last active owner; make another member owner first") ) // Role is a member's role in an org or one of its workspaces. diff --git a/internal/infrastructure/postgres/identities.go b/internal/infrastructure/postgres/identities.go index 0e910f9f4..98b8f3552 100644 --- a/internal/infrastructure/postgres/identities.go +++ b/internal/infrastructure/postgres/identities.go @@ -174,6 +174,11 @@ 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 + } + } n, err := q.UpdateIdentity(ctx, postgresdb.UpdateIdentityParams{ ID: string(id), DisplayName: next.DisplayName, Lifecycle: string(next.Lifecycle), diff --git a/internal/infrastructure/postgres/orgs.go b/internal/infrastructure/postgres/orgs.go index 35efd7627..ad75b7f9c 100644 --- a/internal/infrastructure/postgres/orgs.go +++ b/internal/infrastructure/postgres/orgs.go @@ -140,11 +140,17 @@ func (s *Store) EnsureMembership(ctx context.Context, value org.Membership) erro if _, err := s.GetOrg(ctx, value.OrgID); err != nil { return err } - return s.queries().EnsureMembership(ctx, postgresdb.EnsureMembershipParams{ + params := postgresdb.EnsureMembershipParams{ IdentityID: string(value.IdentityID), OrgID: string(value.OrgID), WorkspaceID: workspace, Role: string(value.Role), + } + if value.WorkspaceID != "" || value.Role == org.RoleOwner { + return s.queries().EnsureMembership(ctx, params) + } + return s.guardOwners(ctx, string(value.IdentityID), string(value.OrgID), func(q *postgresdb.Queries) error { + return q.EnsureMembership(ctx, params) }) } @@ -187,8 +193,14 @@ func (s *Store) RemoveMembership(ctx context.Context, value org.Membership) erro if value.IdentityID == "" || value.OrgID == "" { return fmt.Errorf("%w: identity and org are required", org.ErrInvalidMembership) } - return s.queries().RemoveMembership(ctx, postgresdb.RemoveMembershipParams{ + params := postgresdb.RemoveMembershipParams{ IdentityID: string(value.IdentityID), OrgID: string(value.OrgID), WorkspaceID: string(value.WorkspaceID), + } + if value.WorkspaceID != "" { + return s.queries().RemoveMembership(ctx, params) + } + return s.guardOwners(ctx, string(value.IdentityID), string(value.OrgID), func(q *postgresdb.Queries) error { + return q.RemoveMembership(ctx, params) }) } diff --git a/internal/infrastructure/postgres/owners_guard.go b/internal/infrastructure/postgres/owners_guard.go new file mode 100644 index 000000000..9d8ff023e --- /dev/null +++ b/internal/infrastructure/postgres/owners_guard.go @@ -0,0 +1,64 @@ +package postgres + +import ( + "context" + + "github.com/jackc/pgx/v5" + + "github.com/samcharles93/archie-core/internal/domain/org" + "github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb" +) + +// keepActiveOwner refuses, inside tx, a change after which an org leaving owns +// org-wide (only orgID, when it is set) has no other active owner. The owner rows are locked first, so two +// owners suspending or removing each other concurrently serialise and the +// second sees the first's change. +func keepActiveOwner(ctx context.Context, tx pgx.Tx, leaving, orgID string) error { + rows, err := tx.Query(ctx, `SELECT org_id FROM memberships + WHERE identity_id = $1 AND workspace_id IS NULL AND role = 'owner' AND ($2 = '' OR org_id = $2)`, leaving, orgID) + if err != nil { + return err + } + orgIDs, err := pgx.CollectRows(rows, pgx.RowTo[string]) + if err != nil { + return err + } + if len(orgIDs) == 0 { + return nil + } + if _, err := tx.Exec(ctx, `SELECT 1 FROM memberships + WHERE org_id = ANY($1) AND workspace_id IS NULL AND role = 'owner' + ORDER BY org_id, identity_id FOR UPDATE`, orgIDs); err != nil { + return err + } + var stranded int + err = tx.QueryRow(ctx, `SELECT count(*) FROM unnest($1::text[]) AS o(org_id) + WHERE NOT EXISTS ( + SELECT 1 FROM memberships m JOIN identities i ON i.id = m.identity_id + WHERE m.org_id = o.org_id AND m.workspace_id IS NULL AND m.role = 'owner' + AND i.lifecycle = 'active' AND m.identity_id <> $2)`, orgIDs, leaving).Scan(&stranded) + if err != nil { + return err + } + if stranded > 0 { + return org.ErrLastOwner + } + return nil +} + +// guardOwners runs fn in a transaction after keepActiveOwner allows leaving +// to stop owning orgID. +func (s *Store) guardOwners(ctx context.Context, leaving, orgID string, fn func(*postgresdb.Queries) error) error { + tx, err := s.pool.Begin(ctx) + if err != nil { + return err + } + defer func() { _ = tx.Rollback(ctx) }() + if err := keepActiveOwner(ctx, tx, leaving, orgID); err != nil { + return err + } + if err := fn(postgresdb.New(tx)); err != nil { + return err + } + return tx.Commit(ctx) +} diff --git a/internal/infrastructure/staterpc/identities.go b/internal/infrastructure/staterpc/identities.go index f754f1983..687ce1a4d 100644 --- a/internal/infrastructure/staterpc/identities.go +++ b/internal/infrastructure/staterpc/identities.go @@ -10,6 +10,7 @@ import ( pb "github.com/samcharles93/archie-core/internal/contracts/state/v1" "github.com/samcharles93/archie-core/internal/domain/identity" + "github.com/samcharles93/archie-core/internal/domain/org" ) func (s *server) ListIdentities(ctx context.Context, _ *pb.ListIdentitiesRequest) (*pb.ListIdentitiesResponse, error) { @@ -231,6 +232,8 @@ func auditProto(value identity.Audit) *pb.IdentityAudit { func identityStatus(err error) error { switch { + case errors.Is(err, org.ErrLastOwner): + return mapError(err) case errors.Is(err, identity.ErrNotFound): return status.Error(codes.NotFound, err.Error()) case errors.Is(err, identity.ErrConflict): @@ -243,6 +246,9 @@ func identityStatus(err error) error { } func identityClientError(err error) error { + if st, ok := status.FromError(err); ok && sentinelForStatus(st) != nil { + return sentinelForStatus(st) + } switch status.Code(err) { case codes.NotFound: return identity.ErrNotFound diff --git a/internal/infrastructure/staterpc/values.go b/internal/infrastructure/staterpc/values.go index 5a5399b3f..fa3a171f5 100644 --- a/internal/infrastructure/staterpc/values.go +++ b/internal/infrastructure/staterpc/values.go @@ -521,6 +521,7 @@ var wireErrors = []struct { {storecontract.ErrCallDepthExceeded, codes.FailedPrecondition, storecontract.ErrCallDepthExceeded.Error()}, {storecontract.ErrSourcePathTaken, codes.AlreadyExists, msgSourcePathTaken}, {org.ErrInvalidWorkspace, codes.InvalidArgument, org.ErrInvalidWorkspace.Error()}, + {org.ErrLastOwner, codes.FailedPrecondition, org.ErrLastOwner.Error()}, {storecontract.ErrHarnessSecretNotFound, codes.NotFound, msgHarnessSecretNotFound}, {storecontract.ErrRereviewCapReached, codes.FailedPrecondition, msgRereviewCapReached}, {storepkg.ErrNotFound, codes.NotFound, storepkg.ErrNotFound.Error()}, diff --git a/internal/webui/api_identities.go b/internal/webui/api_identities.go index d3a3a5afe..0ca892ab9 100644 --- a/internal/webui/api_identities.go +++ b/internal/webui/api_identities.go @@ -10,6 +10,7 @@ import ( "github.com/samcharles93/archie-core/internal/domain/access" "github.com/samcharles93/archie-core/internal/domain/identity" + "github.com/samcharles93/archie-core/internal/domain/org" ) type identityRequest struct { @@ -112,7 +113,7 @@ func writeIdentityError(w http.ResponseWriter, err error) { switch { case errors.Is(err, identity.ErrNotFound): code = http.StatusNotFound - case errors.Is(err, identity.ErrConflict): + case errors.Is(err, identity.ErrConflict), errors.Is(err, org.ErrLastOwner): code = http.StatusConflict case errors.Is(err, identity.ErrInvalid), errors.Is(err, identity.ErrIllegalTransition), errors.Is(err, identity.ErrSystemImmutable): code = http.StatusBadRequest diff --git a/internal/webui/api_orgs.go b/internal/webui/api_orgs.go index d9976ca13..8ccb2fbf1 100644 --- a/internal/webui/api_orgs.go +++ b/internal/webui/api_orgs.go @@ -399,7 +399,8 @@ func writeOrgError(w http.ResponseWriter, err error) { http.Error(w, err.Error(), http.StatusBadRequest) case errors.Is(err, org.ErrOrgNotFound): http.Error(w, err.Error(), http.StatusNotFound) - case errors.Is(err, org.ErrOrgExists), errors.Is(err, org.ErrWorkspaceExists), errors.Is(err, org.ErrMembershipExists): + case errors.Is(err, org.ErrOrgExists), errors.Is(err, org.ErrWorkspaceExists), errors.Is(err, org.ErrMembershipExists), + errors.Is(err, org.ErrLastOwner): http.Error(w, err.Error(), http.StatusConflict) default: writeControlPlaneError(w, err)