feat(governance): let owners rename the organisation and workspaces

Adds the organisation routes the single binary's dashboard needs (list, get, workspace list and create) plus owner-only renames of the organisation and its workspaces. A rename is guarded by the version the caller read, writes only the display label, and appends an actor-attributed event in governance.org_events in the same transaction. The Organisation page shows those name changes, and a deep link is no longer replaced by the landing page while the router is still resolving it.

Refs #2077
This commit is contained in:
sam committed 2026-11-20 21:10:34 +11:00
1 parent 904c510246
commit 064eeab748
20 files changed
+1408 -34

No files matched your search

+11
View File
@@ -238,6 +238,17 @@ func (p Principal) Role(ws WorkspaceID) Role {
return orgRole
}
// RoleIn returns the principal's org-wide role in id, or "" when it holds no
// org-wide membership there. A workspace membership does not count.
func (p Principal) RoleIn(id OrgID) Role {
for _, m := range p.Memberships {
if m.OrgID == id && m.WorkspaceID == "" {
return m.Role
}
}
return ""
}
// InstanceAdmin reports whether the principal owns the default operating org.
func (p Principal) InstanceAdmin() bool {
for _, m := range p.Memberships {
+4 -1
View File
@@ -619,10 +619,13 @@ func (m *Module) capabilities(ctx context.Context, _ *struct{}) (*httpapi.Reply[
"home", "tasks", "work_requests", "logs", "skills", "curators", "channels",
"captures", "mappings", "bindings", "workflow_editor", "extension_catalogue", "model_aliases",
"system_status", "task_execution", "organisations", "tools", "plugins", "container_runtime", "agent_profiles",
"org", "org_members", "org_agents", "org_workspaces", "org_policies", "org_denials", "org_audit", "org_usage", "org_config",
"org_members", "org_agents", "org_policies", "org_denials", "org_audit", "org_usage", "org_config",
} {
sections[name] = false
}
// Every member reads the organisation they belong to and its workspaces.
sections["org"] = signedIn
sections["org_workspaces"] = signedIn
return httpapi.OK(capabilitiesBody{Sections: sections}), nil
}
+5
View File
@@ -255,6 +255,7 @@ type Module struct {
store *store.Store
log *slog.Logger
credentials Credentials
authorizer Authorizer
oidc *oidcLogin
}
@@ -268,6 +269,10 @@ func NewModule(db *sqlx.DB, log *slog.Logger, orgID string) *Module {
// resolves through.
func (m *Module) UseCredentials(c Credentials) { m.credentials = c }
// UseAuthorizer gives the module the live policy chain that administrative
// writes are checked against.
func (m *Module) UseAuthorizer(a Authorizer) { m.authorizer = a }
// AgentModel returns the organisation's agent model.
func (m *Module) AgentModel(ctx context.Context) (Model, error) {
return m.AgentModelForAlias(ctx, "")
@@ -18,6 +18,8 @@ var (
ErrAlreadyExists = errors.New("already exists")
// ErrLastOwner means a membership or lifecycle change would leave an org without an active owner.
ErrLastOwner = errors.New("last active owner")
// ErrVersionConflict means the row changed after the caller read it.
ErrVersionConflict = errors.New("version conflict")
// ErrSetupComplete means the instance already has a registered owner account.
ErrSetupComplete = errors.New("setup complete")
// ErrCredentialRejected means presented credentials were invalid, locked, or inactive.
+112 -3
View File
@@ -14,6 +14,7 @@ import (
type OrgRow struct {
ID string `db:"id"`
Name string `db:"name"`
Version int64 `db:"version"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
@@ -24,10 +25,26 @@ type WorkspaceRow struct {
OrgID string `db:"org_id"`
Name string `db:"name"`
Environment string `db:"environment"`
Version int64 `db:"version"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
// OrgEventRow is one appended name change in governance.org_events. WorkspaceID
// is empty when the event renamed the organisation itself.
type OrgEventRow struct {
ID int64 `db:"id"`
OrgID string `db:"org_id"`
WorkspaceID string `db:"workspace_id"`
Type string `db:"event_type"`
ActorID string `db:"actor_id"`
ActorName string `db:"actor_name"`
RequestID string `db:"request_id"`
OldName string `db:"old_name"`
NewName string `db:"new_name"`
At time.Time `db:"at"`
}
// MembershipRow is a role assignment in governance.memberships.
type MembershipRow struct {
IdentityID string `db:"identity_id"`
@@ -80,7 +97,7 @@ func (s *Store) CreateOrg(ctx context.Context, id, name, defaultWorkspaceID, own
// GetOrg returns one org row; ok is false when not found.
func (s *Store) GetOrg(ctx context.Context, id string) (OrgRow, bool, error) {
var out OrgRow
err := s.db.GetContext(ctx, &out, `SELECT id, name, created_at, updated_at FROM governance.orgs WHERE id = $1`, id)
err := s.db.GetContext(ctx, &out, `SELECT id, name, version, created_at, updated_at FROM governance.orgs WHERE id = $1`, id)
if errors.Is(err, sql.ErrNoRows) {
return OrgRow{}, false, nil
}
@@ -94,7 +111,7 @@ func (s *Store) GetOrg(ctx context.Context, id string) (OrgRow, bool, error) {
func (s *Store) ListOrgs(ctx context.Context) ([]OrgRow, error) {
var out []OrgRow
if err := s.db.SelectContext(ctx, &out, `
SELECT id, name, created_at, updated_at FROM governance.orgs ORDER BY created_at, id`); err != nil {
SELECT id, name, version, created_at, updated_at FROM governance.orgs ORDER BY created_at, id`); err != nil {
return nil, fmt.Errorf("list orgs: %w", err)
}
return out, nil
@@ -122,13 +139,105 @@ func (s *Store) CreateWorkspace(ctx context.Context, w WorkspaceRow) error {
func (s *Store) ListWorkspaces(ctx context.Context, orgID string) ([]WorkspaceRow, error) {
var out []WorkspaceRow
if err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, name, environment, created_at, updated_at
SELECT id, org_id, name, environment, version, created_at, updated_at
FROM governance.workspaces WHERE org_id = $1 ORDER BY created_at, id`, orgID); err != nil {
return nil, fmt.Errorf("list workspaces: %w", err)
}
return out, nil
}
// RenameOrg changes an org's display name when its version still matches
// expected and appends event in the same transaction. A rename to the current
// name writes nothing, so no audit entry claims a change that did not happen.
func (s *Store) RenameOrg(ctx context.Context, id, name string, expected int64, event OrgEventRow) (OrgRow, error) {
var out OrgRow
err := s.withTx(ctx, func(tx *sqlx.Tx) error {
var current OrgRow
if err := tx.GetContext(ctx, &current, `
SELECT id, name, version, created_at, updated_at FROM governance.orgs
WHERE id = $1 FOR UPDATE`, id); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
}
return fmt.Errorf("read org: %w", err)
}
if current.Version != expected {
return ErrVersionConflict
}
if current.Name == name {
out = current
return nil
}
if err := tx.GetContext(ctx, &out, `
UPDATE governance.orgs SET name = $2, version = version + 1, updated_at = now()
WHERE id = $1
RETURNING id, name, version, created_at, updated_at`, id, name); err != nil {
return fmt.Errorf("rename org: %w", err)
}
event.OrgID, event.OldName, event.NewName = id, current.Name, name
return insertOrgEvent(ctx, tx, event)
})
return out, err
}
// RenameWorkspace changes one workspace's display name inside orgID when its
// version still matches expected and appends event in the same transaction.
func (s *Store) RenameWorkspace(ctx context.Context, orgID, id, name string, expected int64, event OrgEventRow) (WorkspaceRow, error) {
var out WorkspaceRow
err := s.withTx(ctx, func(tx *sqlx.Tx) error {
var current WorkspaceRow
if err := tx.GetContext(ctx, &current, `
SELECT id, org_id, name, environment, version, created_at, updated_at
FROM governance.workspaces WHERE org_id = $1 AND id = $2 FOR UPDATE`, orgID, id); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
}
return fmt.Errorf("read workspace: %w", err)
}
if current.Version != expected {
return ErrVersionConflict
}
if current.Name == name {
out = current
return nil
}
if err := tx.GetContext(ctx, &out, `
UPDATE governance.workspaces SET name = $3, version = version + 1, updated_at = now()
WHERE org_id = $1 AND id = $2
RETURNING id, org_id, name, environment, version, created_at, updated_at`,
orgID, id, name); err != nil {
return fmt.Errorf("rename workspace: %w", err)
}
event.OrgID, event.WorkspaceID, event.OldName, event.NewName = orgID, id, current.Name, name
return insertOrgEvent(ctx, tx, event)
})
return out, err
}
func insertOrgEvent(ctx context.Context, tx *sqlx.Tx, ev OrgEventRow) error {
_, err := tx.ExecContext(ctx, `
INSERT INTO governance.org_events
(org_id, workspace_id, event_type, actor_id, actor_name, request_id, old_name, new_name)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
ev.OrgID, ev.WorkspaceID, ev.Type, ev.ActorID, ev.ActorName, ev.RequestID, ev.OldName, ev.NewName)
return err
}
// ListOrgEvents returns an org's appended name changes, newest first.
func (s *Store) ListOrgEvents(ctx context.Context, orgID string, limit int) ([]OrgEventRow, error) {
if limit < 1 || limit > 200 {
limit = 50
}
var out []OrgEventRow
if err := s.db.SelectContext(ctx, &out, `
SELECT id, org_id, workspace_id, event_type, actor_id, actor_name, request_id, old_name, new_name, at
FROM governance.org_events WHERE org_id = $1
ORDER BY at DESC, id DESC LIMIT $2`, orgID, limit); err != nil {
return nil, fmt.Errorf("list org events: %w", err)
}
return out, nil
}
// keepActiveOwner refuses, inside tx, a change after which an org leaving owns
// org-wide (scoped to orgID when non-empty) has no other active owner.
func keepActiveOwner(ctx context.Context, tx *sqlx.Tx, leaving, orgID string) error {
+69 -13
View File
@@ -5,6 +5,9 @@ import (
"errors"
"fmt"
"strings"
"time"
"unicode"
"unicode/utf8"
"github.com/samcharles93/archie-core/internal/platform/stableid"
)
@@ -29,12 +32,37 @@ var (
ErrInvalidWorkspace = errors.New("org: invalid workspace")
ErrInvalidAssignment = errors.New("org: invalid agent assignment")
ErrOrgNotFound = errors.New("org: org not found")
ErrWorkspaceNotFound = errors.New("org: workspace not found")
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")
ErrNotOwner = errors.New("org: only an owner may change this")
ErrNameChanged = errors.New("org: the name changed after it was read")
)
// MaxNameLength bounds a display name so it stays a label, not a paragraph.
const MaxNameLength = 80
// ValidateName trims a display name and rejects one that is blank, longer than
// MaxNameLength, or carries control or format characters: a name is rendered
// as text, and a bidi override could make it read as a different name.
func ValidateName(name string) (string, error) {
trimmed := strings.TrimSpace(name)
switch {
case trimmed == "":
return "", errors.New("a name is required")
case utf8.RuneCountInString(trimmed) > MaxNameLength:
return "", fmt.Errorf("a name is at most %d characters", MaxNameLength)
}
for _, r := range trimmed {
if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) {
return "", errors.New("a name contains a character that is not allowed")
}
}
return trimmed, nil
}
// Role is a member's role in an organisation or one of its workspaces.
type Role string
@@ -54,46 +82,70 @@ func (r Role) Validate() error {
return nil
}
// Org is a tenant.
// Org is a tenant. Version is the revision a rename is guarded by.
type Org struct {
ID OrgID `json:"id"`
Name string `json:"name"`
ID OrgID `json:"id"`
Name string `json:"name"`
Version int64 `json:"version"`
}
// Validate requires an org to have an ID and a name without slashes.
// Validate requires an org to have an ID and a well-formed name.
func (o Org) Validate() error {
if o.ID == "" || strings.TrimSpace(o.Name) == "" {
return fmt.Errorf("%w: ID and name are required", ErrInvalidOrg)
if o.ID == "" {
return fmt.Errorf("%w: an ID is required", ErrInvalidOrg)
}
if strings.Contains(string(o.ID), "/") {
return fmt.Errorf("%w: ID must not contain a slash", ErrInvalidOrg)
return fmt.Errorf("%w: the ID must not contain a slash", ErrInvalidOrg)
}
if _, err := ValidateName(o.Name); err != nil {
return fmt.Errorf("%w: %w", ErrInvalidOrg, err)
}
return nil
}
// Workspace divides an organisation. Environment is a free-form attribute
// policies can test.
// policies can test, and Version is the revision a rename is guarded by.
type Workspace struct {
ID WorkspaceID `json:"id"`
OrgID OrgID `json:"org_id"`
Name string `json:"name"`
Environment string `json:"environment,omitempty"`
Version int64 `json:"version"`
}
// Validate requires a workspace to belong to an org and have a name without slashes.
// Validate requires a workspace to belong to an org and have a well-formed name.
func (w Workspace) Validate() error {
if w.OrgID == "" {
return fmt.Errorf("%w: no org", ErrInvalidWorkspace)
}
if strings.TrimSpace(w.Name) == "" {
return fmt.Errorf("%w: no name", ErrInvalidWorkspace)
if _, err := ValidateName(w.Name); err != nil {
return fmt.Errorf("%w: %w", ErrInvalidWorkspace, err)
}
if strings.Contains(string(w.ID), "/") || strings.Contains(string(w.OrgID), "/") {
return fmt.Errorf("%w: IDs must not contain a slash", ErrInvalidWorkspace)
return fmt.Errorf("%w: the IDs must not contain a slash", ErrInvalidWorkspace)
}
return nil
}
// mayRename reports whether p is a person who owns id org-wide. A shared token,
// a bot or service account, an admin, and a workspace owner may not.
func (p Principal) mayRename(id OrgID) bool {
return p.Kind == KindUser && p.RoleIn(id) == RoleOwner
}
// OrgEvent is one appended name change: the organisation itself when
// WorkspaceID is empty, otherwise one of its workspaces.
type OrgEvent struct {
ID int64 `json:"id"`
Kind string `json:"kind"`
WorkspaceID WorkspaceID `json:"workspace_id,omitempty"`
ActorID IdentityID `json:"actor_id"`
ActorName string `json:"actor_name"`
OldName string `json:"old_name"`
NewName string `json:"new_name"`
At time.Time `json:"at"`
}
// Membership gives an identity a role in an org, or in one workspace of it
// when WorkspaceID is set.
type Membership struct {
@@ -194,11 +246,15 @@ type OrgRepository interface { //nolint:interfacebloat // one tenant-boundary st
}
// OrgAPI is the read and write org surface exposed to callers.
type OrgAPI interface {
type OrgAPI interface { //nolint:interfacebloat // one tenant-boundary API: orgs, workspaces and name history
ListOrgs(context.Context) ([]Org, error)
GetOrg(context.Context, OrgID) (Org, error)
RenameOrg(context.Context, OrgID, string, int64, IdentityID) (Org, error)
ListWorkspaces(context.Context, OrgID) ([]Workspace, error)
CreateWorkspace(context.Context, Workspace) (Workspace, error)
RenameWorkspace(context.Context, OrgID, WorkspaceID, string, int64, IdentityID) (Workspace, error)
ListOrgEvents(context.Context, OrgID, int) ([]OrgEvent, error)
ListMembers(context.Context, OrgID) ([]Member, error)
EnsureMembership(context.Context, Membership) error
RemoveMembership(context.Context, Membership) error
+97
View File
@@ -0,0 +1,97 @@
package governance
import (
"strings"
"testing"
)
// TestMayRename guards the boundary that decides who may change an
// organisation's names: a person who owns it org-wide, and nobody else.
func TestMayRename(t *testing.T) {
const (
org = OrgID("org-a")
home = OrgID("org-sys")
)
tests := []struct {
name string
p Principal
want bool
}{
{
name: "org owner",
p: Principal{Kind: KindUser, Org: org, Memberships: []Membership{{OrgID: org, Role: RoleOwner}}},
want: true,
},
{
name: "owner of another org",
p: Principal{Kind: KindUser, Org: org, Memberships: []Membership{{OrgID: home, Role: RoleOwner}}},
},
{
name: "admin in the org",
p: Principal{Kind: KindUser, Org: org, Memberships: []Membership{{OrgID: org, Role: RoleAdmin}}},
},
{
name: "owner of one workspace only",
p: Principal{Kind: KindUser, Org: org, Memberships: []Membership{
{OrgID: org, WorkspaceID: "default", Role: RoleOwner},
}},
},
{
name: "shared system token acting as an owner",
p: Principal{Kind: KindSystem, Org: org, Memberships: []Membership{{OrgID: org, Role: RoleOwner}}},
},
{
name: "bot holding the owner role",
p: Principal{Kind: KindBot, Org: org, Memberships: []Membership{{OrgID: org, Role: RoleOwner}}},
},
{
name: "no membership",
p: Principal{Kind: KindUser, Org: home},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.p.mayRename(org); got != tt.want {
t.Fatalf("mayRename(%q) = %v, want %v", org, got, tt.want)
}
})
}
}
// TestValidateName guards the label grammar: a name is trimmed, bounded, and
// cannot carry a control or bidi character that would render it as another
// name.
func TestValidateName(t *testing.T) {
tests := []struct {
name string
in string
want string
wantErr bool
}{
{name: "ordinary name", in: "Catlow Ltd", want: "Catlow Ltd"},
{name: "trimmed", in: " Acme ", want: "Acme"},
{name: "unicode", in: "Grüne Straße", want: "Grüne Straße"},
{name: "at the limit", in: strings.Repeat("a", MaxNameLength), want: strings.Repeat("a", MaxNameLength)},
{name: "blank", in: " ", wantErr: true},
{name: "past the limit", in: strings.Repeat("a", MaxNameLength+1), wantErr: true},
{name: "newline", in: "Acme\nLtd", wantErr: true},
{name: "bidi override", in: "Acme\u202Egnp.exe", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ValidateName(tt.in)
if tt.wantErr {
if err == nil {
t.Fatalf("ValidateName(%q) = %q, want an error", tt.in, got)
}
return
}
if err != nil {
t.Fatalf("ValidateName(%q): %v", tt.in, err)
}
if got != tt.want {
t.Fatalf("ValidateName(%q) = %q, want %q", tt.in, got, tt.want)
}
})
}
}
+300
View File
@@ -0,0 +1,300 @@
package governance
import (
"context"
"errors"
"net/http"
"time"
"github.com/danielgtaylor/huma/v2"
"github.com/samcharles93/archie-core/internal/platform/httpapi"
)
// orgView is an organisation as its caller sees it: the org-wide role decides
// which controls the dashboard offers, and the server enforces the same rule.
type orgView struct {
ID OrgID `json:"id"`
Name string `json:"name"`
Version int64 `json:"version"`
Role Role `json:"role,omitempty"`
}
func viewOf(value Org, role Role) orgView {
return orgView{ID: value.ID, Name: value.Name, Version: value.Version, Role: role}
}
type orgsBody struct {
Orgs []orgView `json:"orgs"`
Current OrgID `json:"current"`
InstanceAdmin bool `json:"instance_admin"`
MemberOrgs []OrgID `json:"member_orgs"`
}
type orgBody struct {
Org orgView `json:"org"`
}
type workspacesBody struct {
Workspaces []Workspace `json:"workspaces"`
}
type workspaceBody struct {
Workspace Workspace `json:"workspace"`
}
type orgEventsBody struct {
Events []OrgEvent `json:"events"`
}
type orgPath struct {
ID string `path:"id" doc:"Organisation ID"`
}
type createWorkspaceInput struct {
ID string `path:"id" doc:"Organisation ID"`
Body struct {
ID string `json:"id" doc:"Workspace ID, permanent for the workspace's life"`
Name string `json:"name" doc:"Display name"`
Environment string `json:"environment,omitempty" doc:"Free-form attribute policies can test"`
}
}
type renameInput struct {
ID string `path:"id" doc:"Organisation ID"`
Body struct {
Name string `json:"name" doc:"The new display name"`
ExpectedVersion int64 `json:"expected_version" doc:"The version the caller read, so a stale edit is refused"`
}
}
type renameWorkspaceInput struct {
ID string `path:"id" doc:"Organisation ID"`
Workspace string `path:"workspace" doc:"Workspace ID"`
Body struct {
Name string `json:"name" doc:"The new display name"`
ExpectedVersion int64 `json:"expected_version" doc:"The version the caller read, so a stale edit is refused"`
}
}
type listEventsInput struct {
ID string `path:"id" doc:"Organisation ID"`
Limit int `query:"limit" default:"50" doc:"How many changes to return, at most 200"`
}
// RegisterOrganisations adds the organisation and workspace routes the
// dashboard's Organisation area uses: reading, creating a workspace, renaming
// either, and the record of name changes. Every route acts in the one
// organisation the caller's request acts in.
func (m *Module) RegisterOrganisations(api huma.API) {
tags := []string{"Organisations"}
signedIn := func(id, method, path, summary string, status int) huma.Operation {
return httpapi.SignedIn(huma.Operation{
OperationID: id, Method: method, Path: path, Summary: summary,
Tags: tags, DefaultStatus: status, MaxBodyBytes: 16 << 10,
})
}
huma.Register(api, signedIn("list-orgs", http.MethodGet, "/api/orgs", "List the organisation the caller acts in", 0), m.listOrgs)
huma.Register(api, signedIn("get-org", http.MethodGet, "/api/orgs/{id}", "Get an organisation", 0), m.getOrg)
huma.Register(api, signedIn("rename-org", http.MethodPatch, "/api/orgs/{id}", "Rename an organisation", 0), m.renameOrg)
huma.Register(api, signedIn("list-org-workspaces", http.MethodGet, "/api/orgs/{id}/workspaces", "List an organisation's workspaces", 0), m.listOrgWorkspaces)
huma.Register(api, signedIn("create-org-workspace", http.MethodPost, "/api/orgs/{id}/workspaces", "Create a workspace", http.StatusCreated), m.createOrgWorkspace)
huma.Register(api, signedIn("rename-org-workspace", http.MethodPatch, "/api/orgs/{id}/workspaces/{workspace}", "Rename a workspace", 0), m.renameOrgWorkspace)
huma.Register(api, signedIn("list-org-events", http.MethodGet, "/api/orgs/{id}/history", "List the organisation's name changes", 0), m.listOrgEvents)
}
// caller returns the principal a request acts as. Every organisation route is
// signed in, so a missing principal means the middleware is misconfigured.
func caller(ctx context.Context) (Principal, error) {
p, ok := PrincipalFromContext(ctx)
if !ok {
return Principal{}, huma.Error401Unauthorized("Sign in to manage an organisation.")
}
return p, nil
}
// actingOrg returns the caller when id is the organisation it acts in. This
// binary serves one operating organisation, so another one reads as not found
// rather than confirming that it exists.
func actingOrg(ctx context.Context, id OrgID) (Principal, error) {
p, err := caller(ctx)
if err != nil {
return Principal{}, err
}
if id != p.Org || !p.Member(id) {
return Principal{}, huma.Error404NotFound("Organisation not found.")
}
return p, nil
}
// ownerOf returns the caller when it owns id org-wide. The policy chain is
// consulted too, so a forbid an owner wrote is still honoured.
func (m *Module) ownerOf(ctx context.Context, kind ResourceKind, resourceID string, id OrgID, workspace WorkspaceID) (Principal, error) {
p, err := actingOrg(ctx, id)
if err != nil {
return Principal{}, err
}
if !p.mayRename(id) {
return Principal{}, huma.Error403Forbidden("Only an owner of this organisation can rename it.")
}
if err := m.policyAllows(ctx, p, ActionUpdate, kind, resourceID, id, workspace); err != nil {
return Principal{}, err
}
return p, nil
}
// policyAllows evaluates the live chain for one write, so a forbid an operator
// wrote refuses it even when the caller's role would otherwise permit it.
func (m *Module) policyAllows(ctx context.Context, p Principal, action Action, kind ResourceKind, resourceID string, org OrgID, workspace WorkspaceID) error {
if m.authorizer == nil {
return huma.Error503ServiceUnavailable("Access policies are unavailable.")
}
scoped := p
scoped.Org = org
decision := m.authorizer.Authorize(ctx, scoped, action, Resource{
Kind: kind, ID: resourceID, Org: org, Workspace: workspace,
}, AccessContext{Time: time.Now()})
switch {
case decision.Err != nil:
return huma.Error503ServiceUnavailable("Access policies are unavailable.")
case !decision.Allowed:
return huma.Error403Forbidden("An access policy refuses this change.")
}
return nil
}
func (m *Module) listOrgs(ctx context.Context, _ *struct{}) (*httpapi.Reply[orgsBody], error) {
p, err := caller(ctx)
if err != nil {
return nil, err
}
body := orgsBody{Orgs: []orgView{}, Current: p.Org, InstanceAdmin: p.InstanceAdmin(), MemberOrgs: []OrgID{}}
value, err := m.GetOrg(ctx, p.Org)
switch {
case errors.Is(err, ErrOrgNotFound):
return httpapi.OK(body), nil
case err != nil:
return nil, huma.Error500InternalServerError("Couldn't read the organisation.")
}
if p.Member(p.Org) {
body.Orgs = append(body.Orgs, viewOf(value, p.RoleIn(p.Org)))
body.MemberOrgs = append(body.MemberOrgs, p.Org)
}
return httpapi.OK(body), nil
}
func (m *Module) getOrg(ctx context.Context, in *orgPath) (*httpapi.Reply[orgBody], error) {
id := OrgID(in.ID)
p, err := actingOrg(ctx, id)
if err != nil {
return nil, err
}
value, err := m.GetOrg(ctx, id)
if errors.Is(err, ErrOrgNotFound) {
return nil, huma.Error404NotFound("Organisation not found.")
}
if err != nil {
return nil, huma.Error500InternalServerError("Couldn't read the organisation.")
}
return httpapi.OK(orgBody{Org: viewOf(value, p.RoleIn(id))}), nil
}
func (m *Module) renameOrg(ctx context.Context, in *renameInput) (*httpapi.Reply[orgBody], error) {
name, err := ValidateName(in.Body.Name)
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
p, err := m.ownerOf(ctx, KindOrg, in.ID, OrgID(in.ID), "")
if err != nil {
return nil, err
}
value, err := m.RenameOrg(ctx, OrgID(in.ID), name, in.Body.ExpectedVersion, p.IdentityID)
switch {
case errors.Is(err, ErrNameChanged):
return nil, huma.Error409Conflict("The name changed after you opened it. Check the current name and save again.")
case errors.Is(err, ErrNotOwner):
return nil, huma.Error403Forbidden("Only an owner of this organisation can rename it.")
case errors.Is(err, ErrInvalidOrg):
return nil, huma.Error400BadRequest("That name can't be used. Use 1 to 80 characters without control characters.")
case errors.Is(err, ErrOrgNotFound):
return nil, huma.Error404NotFound("Organisation not found.")
case err != nil:
return nil, huma.Error500InternalServerError("Couldn't rename the organisation.")
}
return httpapi.OK(orgBody{Org: viewOf(value, RoleOwner)}), nil
}
func (m *Module) listOrgWorkspaces(ctx context.Context, in *orgPath) (*httpapi.Reply[workspacesBody], error) {
if _, err := actingOrg(ctx, OrgID(in.ID)); err != nil {
return nil, err
}
values, err := m.ListWorkspaces(ctx, OrgID(in.ID))
if err != nil {
return nil, huma.Error500InternalServerError("Couldn't read the workspaces.")
}
return httpapi.OK(workspacesBody{Workspaces: values}), nil
}
func (m *Module) createOrgWorkspace(ctx context.Context, in *createWorkspaceInput) (*httpapi.Reply[workspaceBody], error) {
p, err := actingOrg(ctx, OrgID(in.ID))
if err != nil {
return nil, err
}
if role := p.RoleIn(OrgID(in.ID)); role != RoleOwner && role != RoleAdmin {
return nil, huma.Error403Forbidden("Only an owner or admin can create a workspace.")
}
if err := m.policyAllows(ctx, p, ActionCreate, KindWorkspace, in.Body.ID, OrgID(in.ID), ""); err != nil {
return nil, err
}
value, err := m.CreateWorkspace(ctx, Workspace{
ID: WorkspaceID(in.Body.ID), OrgID: OrgID(in.ID),
Name: in.Body.Name, Environment: in.Body.Environment,
})
switch {
case errors.Is(err, ErrInvalidWorkspace):
return nil, huma.Error400BadRequest("A workspace needs an ID without a slash and a name of 1 to 80 characters.")
case errors.Is(err, ErrWorkspaceExists):
return nil, huma.Error409Conflict("A workspace with that ID already exists in this organisation.")
case errors.Is(err, ErrOrgNotFound):
return nil, huma.Error404NotFound("Organisation not found.")
case err != nil:
return nil, huma.Error500InternalServerError("Couldn't create the workspace.")
}
return httpapi.OK(workspaceBody{Workspace: value}), nil
}
func (m *Module) renameOrgWorkspace(ctx context.Context, in *renameWorkspaceInput) (*httpapi.Reply[workspaceBody], error) {
name, err := ValidateName(in.Body.Name)
if err != nil {
return nil, huma.Error400BadRequest(err.Error())
}
p, err := m.ownerOf(ctx, KindWorkspace, in.Workspace, OrgID(in.ID), WorkspaceID(in.Workspace))
if err != nil {
return nil, err
}
value, err := m.RenameWorkspace(ctx, OrgID(in.ID), WorkspaceID(in.Workspace), name, in.Body.ExpectedVersion, p.IdentityID)
switch {
case errors.Is(err, ErrNameChanged):
return nil, huma.Error409Conflict("The name changed after you opened it. Check the current name and save again.")
case errors.Is(err, ErrNotOwner):
return nil, huma.Error403Forbidden("Only an owner of this organisation can rename its workspaces.")
case errors.Is(err, ErrInvalidWorkspace):
return nil, huma.Error400BadRequest("That name can't be used. Use 1 to 80 characters without control characters.")
case errors.Is(err, ErrWorkspaceNotFound):
return nil, huma.Error404NotFound("Workspace not found.")
case err != nil:
return nil, huma.Error500InternalServerError("Couldn't rename the workspace.")
}
return httpapi.OK(workspaceBody{Workspace: value}), nil
}
func (m *Module) listOrgEvents(ctx context.Context, in *listEventsInput) (*httpapi.Reply[orgEventsBody], error) {
if _, err := actingOrg(ctx, OrgID(in.ID)); err != nil {
return nil, err
}
values, err := m.ListOrgEvents(ctx, OrgID(in.ID), in.Limit)
if err != nil {
return nil, huma.Error500InternalServerError("Couldn't read the organisation's history.")
}
return httpapi.OK(orgEventsBody{Events: values}), nil
}
+105 -2
View File
@@ -2,6 +2,7 @@ package governance
import (
"context"
"crypto/rand"
"database/sql"
"errors"
"fmt"
@@ -30,6 +31,7 @@ func (m *Module) CreateOrg(ctx context.Context, value Org, owner IdentityID) (Or
if err != nil {
return Org{}, err
}
value.Version = 1
return value, nil
}
@@ -42,7 +44,7 @@ func (m *Module) GetOrg(ctx context.Context, id OrgID) (Org, error) {
if !ok {
return Org{}, ErrOrgNotFound
}
return Org{ID: OrgID(row.ID), Name: row.Name}, nil
return Org{ID: OrgID(row.ID), Name: row.Name, Version: row.Version}, nil
}
// ListOrgs returns every organisation, oldest first.
@@ -53,11 +55,40 @@ func (m *Module) ListOrgs(ctx context.Context) ([]Org, error) {
}
out := make([]Org, 0, len(rows))
for _, r := range rows {
out = append(out, Org{ID: OrgID(r.ID), Name: r.Name})
out = append(out, Org{ID: OrgID(r.ID), Name: r.Name, Version: r.Version})
}
return out, nil
}
// RenameOrg changes an organisation's display name and appends an audit event
// naming the person who made the change. Only an owner of the organisation may.
func (m *Module) RenameOrg(ctx context.Context, id OrgID, name string, expectedVersion int64, actor IdentityID) (Org, error) {
p, ok := PrincipalFromContext(ctx)
if !ok || !p.mayRename(id) {
return Org{}, ErrNotOwner
}
name, err := ValidateName(name)
if err != nil {
return Org{}, fmt.Errorf("%w: %w", ErrInvalidOrg, err)
}
actorName, err := m.actorName(ctx, actor)
if err != nil {
return Org{}, err
}
row, err := m.store.RenameOrg(ctx, string(id), name, expectedVersion, store.OrgEventRow{
Type: "org.renamed", ActorID: string(actor), ActorName: actorName, RequestID: newRequestID("org-rename"),
})
switch {
case errors.Is(err, store.ErrNotFound):
return Org{}, ErrOrgNotFound
case errors.Is(err, store.ErrVersionConflict):
return Org{}, ErrNameChanged
case err != nil:
return Org{}, err
}
return Org{ID: OrgID(row.ID), Name: row.Name, Version: row.Version}, nil
}
// CreateWorkspace adds a workspace to an existing organisation.
func (m *Module) CreateWorkspace(ctx context.Context, value Workspace) (Workspace, error) {
if err := value.Validate(); err != nil {
@@ -77,6 +108,7 @@ func (m *Module) CreateWorkspace(ctx context.Context, value Workspace) (Workspac
case err != nil:
return Workspace{}, err
}
value.Version = 1
return value, nil
}
@@ -93,11 +125,82 @@ func (m *Module) ListWorkspaces(ctx context.Context, id OrgID) ([]Workspace, err
OrgID: OrgID(r.OrgID),
Name: r.Name,
Environment: r.Environment,
Version: r.Version,
})
}
return out, nil
}
// RenameWorkspace changes a workspace's display name and appends an audit event
// naming the person who made the change. Only an owner of its organisation may.
func (m *Module) RenameWorkspace(ctx context.Context, orgID OrgID, id WorkspaceID, name string, expectedVersion int64, actor IdentityID) (Workspace, error) {
p, ok := PrincipalFromContext(ctx)
if !ok || !p.mayRename(orgID) {
return Workspace{}, ErrNotOwner
}
name, err := ValidateName(name)
if err != nil {
return Workspace{}, fmt.Errorf("%w: %w", ErrInvalidWorkspace, err)
}
actorName, err := m.actorName(ctx, actor)
if err != nil {
return Workspace{}, err
}
row, err := m.store.RenameWorkspace(ctx, string(orgID), string(id), name, expectedVersion, store.OrgEventRow{
Type: "workspace.renamed", ActorID: string(actor), ActorName: actorName, RequestID: newRequestID("workspace-rename"),
})
switch {
case errors.Is(err, store.ErrNotFound):
return Workspace{}, ErrWorkspaceNotFound
case errors.Is(err, store.ErrVersionConflict):
return Workspace{}, ErrNameChanged
case err != nil:
return Workspace{}, err
}
return Workspace{
ID: WorkspaceID(row.ID), OrgID: OrgID(row.OrgID), Name: row.Name,
Environment: row.Environment, Version: row.Version,
}, nil
}
// ListOrgEvents returns the organisation's name changes, newest first.
func (m *Module) ListOrgEvents(ctx context.Context, id OrgID, limit int) ([]OrgEvent, error) {
rows, err := m.store.ListOrgEvents(ctx, string(id), limit)
if err != nil {
return nil, err
}
out := make([]OrgEvent, 0, len(rows))
for _, r := range rows {
kind := "org"
if r.WorkspaceID != "" {
kind = "workspace"
}
out = append(out, OrgEvent{
ID: r.ID, Kind: kind, WorkspaceID: WorkspaceID(r.WorkspaceID),
ActorID: IdentityID(r.ActorID), ActorName: r.ActorName,
OldName: r.OldName, NewName: r.NewName, At: r.At,
})
}
return out, nil
}
// actorName is the display name recorded beside an actor ID so an audit row
// still reads when that identity is later renamed or retired.
func (m *Module) actorName(ctx context.Context, id IdentityID) (string, error) {
row, err := m.store.GetIdentity(ctx, string(id))
if errors.Is(err, store.ErrNotFound) {
return string(id), nil
}
if err != nil {
return "", err
}
return row.DisplayName, nil
}
func newRequestID(prefix string) string {
return prefix + ":" + rand.Text()
}
// EnsureMembership grants or updates a membership role in an organisation or workspace.
func (m *Module) EnsureMembership(ctx context.Context, value Membership) error {
if err := value.Validate(); err != nil {