Files
sam 064eeab748 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
2026-11-20 21:10:34 +11:00

301 lines
11 KiB
Go

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
}