feat: several owners per organization, and handing ownership over
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 9m19s
ci / test (pull_request) Successful in 9m25s
ci / build (pull_request) Successful in 15m40s
ci / image (pull_request) Successful in 4m26s

An organization may now have several owners; the unique index allowing
only one is gone. Owners make members owners or take it back, their own
included, through PUT /api/v1/org/members/:user/owner; handing an
organization over is making someone else owner and stepping down. The
last owner cannot step down, and changes serialize on a per-organization
lock so two owners stepping down at once cannot leave none. A former
owner without roles keeps working as Admin. Owners still cannot be
removed while they are owners.

Deleting an account now takes along only the organizations it is the
last owner of, counted under the same lock; it just leaves those with
further owners. The members page offers "Make owner", "Remove as owner"
and "Step down as owner" to owners.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-23 22:38:04 +01:00
1 parent 8d7c1f856c
commit db3ff19983
23 files changed
+558 -115

No files matched your search

+6 -2
View File
@@ -60,7 +60,7 @@ var endpoints = []endpoint{
{method: "GET", path: "/api/v1/me/export", tag: "Account", summary: "Export all personal data (GDPR Art. 15, 20)",
description: "`?format=pdf` returns a PDF instead of JSON.", resp: accountExport{}},
{method: "POST", path: "/api/v1/me/delete", tag: "Account", summary: "Delete the account (GDPR Art. 17)", sessionOnly: true,
description: "Organizations the user owns are deleted with the account, with all their monitors, even when they have other members. Open to suspended accounts and to those that have not accepted the terms.",
description: "Organizations the user is the last owner of are deleted with the account, with all their monitors, even when they have other members; organizations with further owners are left. Open to suspended accounts and to those that have not accepted the terms.",
req: deletionRequest{}, resp: obj{"status": ""}},
{method: "POST", path: "/api/v1/consent", tag: "Account", summary: "Accept the platform's privacy policy and terms", sessionOnly: true,
description: "`versions` are the versions shown, e.g. `privacy:12,terms:14`; `409 consent_outdated` when a document changed meanwhile. Until an account accepted the current versions, other requests of its sessions get `403 consent_required`.",
@@ -189,6 +189,10 @@ var endpoints = []endpoint{
description: "Paged by email.", resp: paged(obj{"members": []memberView{}})},
{method: "DELETE", path: "/api/v1/org/members/:user", tag: "Organization", summary: "Remove a member", perm: "members.manage", sessionOnly: true,
status: http.StatusNoContent},
{method: "PUT", path: "/api/v1/org/members/:user/owner", tag: "Organization", summary: "Make a member an owner, or step down", sessionOnly: true,
perm: "owner",
description: "Only owners decide. `{\"owner\": false}` on oneself steps down; handing over is making someone else owner first. The last owner cannot step down (`409 last_owner`). A former owner without roles becomes Admin.",
req: ownerRequest{}, status: http.StatusNoContent},
{method: "POST", path: "/api/v1/org/members/:user/roles", tag: "Organization", summary: "Assign a role, optionally limited to a group or status page",
description: "Nobody can grant permissions they do not hold.", perm: "members.manage", sessionOnly: true,
req: assignRequest{}, status: http.StatusCreated, resp: obj{"id": uuid.UUID{}}},
@@ -300,7 +304,7 @@ var endpoints = []endpoint{
description: "A suspended account is signed out everywhere and cannot use its API tokens; signing in again only lets it export or delete its data. Platform admins cannot be suspended.",
perm: "platform admin", req: suspensionRequest{}, status: http.StatusNoContent},
{method: "DELETE", path: "/api/v1/admin/users/:id", tag: "Platform", summary: "Delete an account",
description: "Organizations the account owns are deleted with it. Platform admins cannot be deleted.",
description: "Organizations the account is the last owner of are deleted with it. Platform admins cannot be deleted.",
perm: "platform admin", status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/regions", tag: "Platform", summary: "List platform regions", perm: "platform admin",
resp: obj{"regions": []regionView{}}},
+1
View File
@@ -38,6 +38,7 @@ var auditActions = map[string]string{
"POST /api/v1/auth/login/totp": "auth.login",
"POST /api/v1/auth/logout": "auth.logout",
"POST /api/v1/consent": "account.consent",
"PUT /api/v1/org/members/:user/owner": "member.owner",
"POST /api/v1/me/org": "",
"POST /api/v1/me/totp/setup": "",
"POST /api/v1/me/totp/enable": "account.totp_enable",
+7 -5
View File
@@ -249,7 +249,7 @@ func (s *Server) restrictedMe(c *gin.Context, sess *auth.Session) (web.Me, error
return web.Me{}, err
}
me := toWebMe(m)
me.DeletesOrgs, err = s.ownedOrgs(c.Request.Context(), sess.UserID)
me.DeletesOrgs, err = s.lastOwnedOrgs(c.Request.Context(), sess.UserID)
return me, err
}
@@ -342,14 +342,16 @@ func (s *Server) signupConsentView(ctx context.Context) (web.SignupConsent, erro
return web.SignupConsent{Docs: s.consentDocs(ctx, required), Versions: consentVersions(required)}, nil
}
// ownedOrgs names the organizations user owns, which deleting the account
// deletes too.
func (s *Server) ownedOrgs(ctx context.Context, user uuid.UUID) ([]string, error) {
// lastOwnedOrgs names the organizations user is the last owner of, which
// deleting the account deletes too.
func (s *Server) lastOwnedOrgs(ctx context.Context, user uuid.UUID) ([]string, error) {
var out []string
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
owned, err := q.OwnedOrgs(ctx, user)
for _, o := range owned {
out = append(out, fmt.Sprintf("%s (%s)", o.Name, o.Slug))
if o.Owners == 1 {
out = append(out, fmt.Sprintf("%s (%s)", o.Name, o.Slug))
}
}
return err
})
+1 -1
View File
@@ -174,7 +174,7 @@ func TestSuspendedAccount(t *testing.T) {
t.Errorf("console of a suspended account landed on %s", got)
}
_, _, page := back.page("/account/suspended")
if !strings.Contains(page, "Unpaid invoice") || !strings.Contains(page, "Delete account") || !strings.Contains(page, "You own these organizations") {
if !strings.Contains(page, "Unpaid invoice") || !strings.Contains(page, "Delete account") || !strings.Contains(page, "You are the last owner of these organizations") {
t.Error("the suspension page lacks the reason or the way out")
}
st, body := back.do("GET", "/api/v1/org/monitors", nil)
+17 -5
View File
@@ -603,9 +603,9 @@ func purgeOrg(ctx context.Context, q *store.Queries, org uuid.UUID) error {
}
// deleteAccount erases the signed-in user (Art. 17). Organizations the
// user owns go with the account, monitors and all, even when they have
// other members: an organization has exactly one owner, and nobody would be
// left to run it.
// user is the last owner of go with the account, monitors and all, even
// when they have other members: nobody would be left to run them. The user
// just leaves organizations with further owners.
// Suspended accounts and those that have not accepted the terms may do
// this too.
func (s *Server) deleteAccount(c *gin.Context) {
@@ -640,8 +640,8 @@ func (s *Server) deleteAccount(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
}
// eraseAccount deletes u with the organizations u owns and ends u's
// sessions; u leaves the others.
// eraseAccount deletes u with the organizations u is the last owner of and
// ends u's sessions; u leaves the others.
func (s *Server) eraseAccount(ctx context.Context, u store.User) (orgsDeleted int, err error) {
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
owned, err := q.OwnedOrgs(ctx, u.ID)
@@ -649,6 +649,18 @@ func (s *Server) eraseAccount(ctx context.Context, u store.User) (orgsDeleted in
return err
}
for _, o := range owned {
if err := q.LockOrgOwners(ctx, o.ID); err != nil {
return err
}
// Counted again under the lock: another owner may be stepping
// down right now.
n, err := q.CountOwners(ctx, o.ID)
if err != nil {
return err
}
if n > 1 {
continue
}
if err := purgeOrg(ctx, q, o.ID); err != nil {
return err
}
+1 -1
View File
@@ -275,7 +275,7 @@ func TestDeleteAccount(t *testing.T) {
org := uuid.MustParse(owner.orgID())
owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "web", "type": "heartbeat", "interval_seconds": 3600})
other := e.joinVia(t, owner.invite("x@"+uniq("da")+".test", owner.roleID("viewer")))
if _, _, html := owner.page("/settings/security"); !strings.Contains(html, "You own these organizations") {
if _, _, html := owner.page("/settings/security"); !strings.Contains(html, "You are the last owner of these organizations") {
t.Error("the security page does not warn that the organization goes with the account")
}
if st, body := owner.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusOK {
+79
View File
@@ -3,6 +3,7 @@ package api
import (
"errors"
"net/http"
"slices"
"strings"
"time"
@@ -495,3 +496,81 @@ func (s *Server) updatePolicy(c *gin.Context) {
}
var errNoSSOProvider = errors.New("api: no enabled sso provider")
// adminRole is the built-in Admin role.
var adminRole = uuid.MustParse("00000000-0000-0000-0000-00000000a001")
type ownerRequest struct {
Owner bool `json:"owner"`
}
// setOwner makes a member an owner or takes it back, the actor's own
// ownership included: handing an organization over is making someone else
// owner and stepping down. Only owners decide, and the last owner stays.
// A former owner without roles keeps working as Admin.
func (s *Server) setOwner(c *gin.Context) {
target, err := uuid.Parse(c.Param("user"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
var req ownerRequest
if !bind(c, &req) {
return
}
p := current(c)
if !p.Grants.Owner {
fail(c, http.StatusForbidden, "owner_only")
return
}
auditDetail(c, "user_id", target.String())
auditDetail(c, "owner", req.Owner)
ctx := c.Request.Context()
var code string
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
if err := q.LockOrgOwners(ctx, p.Org.ID); err != nil {
return err
}
m, err := q.GetMembership(ctx, store.GetMembershipParams{OrgID: p.Org.ID, UserID: target})
switch {
case errors.Is(err, pgx.ErrNoRows):
code = "not_found"
return nil
case err != nil:
return err
case m.IsOwner == req.Owner:
return nil
}
if !req.Owner {
n, err := q.CountOwners(ctx, p.Org.ID)
if err != nil {
return err
}
if n <= 1 {
code = "last_owner"
return nil
}
assigned, err := q.ListAssignments(ctx, p.Org.ID)
if err != nil {
return err
}
if !slices.ContainsFunc(assigned, func(a store.ListAssignmentsRow) bool { return a.UserID == target }) {
if _, err := q.CreateAssignment(ctx, store.CreateAssignmentParams{OrgID: p.Org.ID, UserID: target, RoleID: adminRole}); err != nil {
return err
}
}
}
_, err = q.SetOwner(ctx, store.SetOwnerParams{OrgID: p.Org.ID, UserID: target, Owner: req.Owner})
return err
})
switch {
case err != nil:
internalError(c, err)
case code == "not_found":
fail(c, http.StatusNotFound, code)
case code != "":
fail(c, http.StatusConflict, code)
default:
c.Status(http.StatusNoContent)
}
}
+85
View File
@@ -0,0 +1,85 @@
package api_test
import (
"net/http"
"strings"
"testing"
"github.com/google/uuid"
)
func TestOwners(t *testing.T) {
e := newEnv(t)
first := e.browser(t)
first.signup("f@"+uniq("ow")+".test", uniq("ow-"))
org := uuid.MustParse(first.orgID())
firstID := first.userIDSelf()
second := e.joinVia(t, first.invite("s@"+uniq("ow")+".test", first.roleID("viewer")))
secondID := second.userIDSelf()
owner := func(b *browser, user uuid.UUID, on bool) (int, map[string]any) {
return b.do("PUT", "/api/v1/org/members/"+user.String()+"/owner", map[string]any{"owner": on})
}
isOwner := func(user uuid.UUID) bool {
return e.count(t, `SELECT count(*) FROM memberships WHERE org_id = $1 AND user_id = $2 AND is_owner`, org, user) == 1
}
// Only owners decide.
st, body := owner(second, secondID, true)
expect(t, "non-owner makes itself owner", st, body, http.StatusForbidden, "owner_only")
st, body = owner(first, firstID, false)
expect(t, "last owner steps down", st, body, http.StatusConflict, "last_owner")
if _, _, html := first.page("/settings/members"); !strings.Contains(html, "Make owner") || strings.Contains(html, "Step down as owner") {
t.Error("the members page offers the wrong owner actions to the only owner")
}
// Handing over: make someone else owner, then step down.
if st, body := owner(first, secondID, true); st != http.StatusNoContent || !isOwner(secondID) {
t.Fatalf("make owner = %d %v", st, body)
}
if st, _ := second.do("PUT", "/api/v1/org/legal/imprint", map[string]any{"markdown": "# Impressum"}); st != http.StatusNoContent {
t.Errorf("new owner manages the organization = %d", st)
}
if _, _, html := first.page("/settings/members"); !strings.Contains(html, "Step down as owner") || !strings.Contains(html, "Remove as owner") {
t.Error("with two owners the page offers neither stepping down nor removing")
}
st, body = first.do("DELETE", "/api/v1/org/members/"+secondID.String(), nil)
expect(t, "remove an owner", st, body, http.StatusForbidden, "owner_cannot_be_removed")
if st, body := owner(first, firstID, false); st != http.StatusNoContent || isOwner(firstID) {
t.Fatalf("step down = %d %v", st, body)
}
// The former owner keeps working as Admin.
if n := e.count(t, `SELECT count(*) FROM role_assignments WHERE org_id = $1 AND user_id = $2 AND role_id = '00000000-0000-0000-0000-00000000a001'`, org, firstID); n != 1 {
t.Errorf("former owner has %d admin assignments, want 1", n)
}
if st, _ := first.do("GET", "/api/v1/org/members", nil); st != http.StatusOK {
t.Errorf("former owner lists members = %d", st)
}
st, body = owner(first, firstID, true)
expect(t, "former owner takes ownership back", st, body, http.StatusForbidden, "owner_only")
st, body = owner(second, secondID, false)
expect(t, "the new last owner steps down", st, body, http.StatusConflict, "last_owner")
// Deleting an account leaves organizations with further owners and
// takes along those it is the last owner of.
if st, body := owner(second, firstID, true); st != http.StatusNoContent {
t.Fatalf("make owner again = %d %v", st, body)
}
if _, _, html := first.page("/settings/security"); strings.Contains(html, "last owner of these organizations") {
t.Error("an organization with another owner is announced as deleted")
}
if st, body := first.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusOK {
t.Fatalf("co-owner deletes account = %d %v", st, body)
}
if e.count(t, `SELECT count(*) FROM orgs WHERE id = $1`, org) != 1 || !isOwner(secondID) {
t.Fatal("the organization did not stay with its other owner")
}
if _, _, html := second.page("/settings/security"); !strings.Contains(html, "last owner of these organizations") {
t.Error("the last owner is not warned")
}
if st, body := second.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusOK {
t.Fatalf("last owner deletes account = %d %v", st, body)
}
if e.count(t, `SELECT count(*) FROM orgs WHERE id = $1`, org) != 0 {
t.Error("the organization survived its last owner")
}
}
+9 -2
View File
@@ -256,7 +256,7 @@ func (s *Server) securityPage(c *gin.Context) {
internalError(c, err)
return
}
if me.DeletesOrgs, err = s.ownedOrgs(ctx, sess.UserID); err != nil {
if me.DeletesOrgs, err = s.lastOwnedOrgs(ctx, sess.UserID); err != nil {
internalError(c, err)
return
}
@@ -400,19 +400,26 @@ func (s *Server) membersView(c *gin.Context, p *principal, page web.Page, me web
var (
roles []store.Role
pending []store.ListPendingInvitationsRow
owners int64
)
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
if roles, err = q.ListRoles(ctx); err != nil {
return err
}
if owners, err = q.CountOwners(ctx, p.Org.ID); err != nil {
return err
}
pending, err = q.ListPendingInvitations(ctx)
return err
})
if err != nil {
return nil, err
}
v := web.MembersView{CanManage: p.Grants.Can(authz.MembersManage), Pager: pager(c, info)}
v := web.MembersView{
CanManage: p.Grants.Can(authz.MembersManage), Pager: pager(c, info),
IsOwner: p.Grants.Owner, Self: p.UserID.String(), Owners: int(owners),
}
scopeNames, scopes, err := s.scopeOptions(ctx, p)
if err != nil {
return nil, err
+1
View File
@@ -242,6 +242,7 @@ func (s *Server) Mount(r gin.IRouter) {
org.GET("/members", can(authz.MembersRead), s.listMembers)
org.DELETE("/members/:user", sessionOnly(), can(authz.MembersManage), s.removeMember)
org.PUT("/members/:user/owner", sessionOnly(), s.setOwner)
org.POST("/members/:user/roles", sessionOnly(), can(authz.MembersManage), s.assignRole)
org.DELETE("/assignments/:id", sessionOnly(), can(authz.MembersManage), s.unassignRole)