diff --git a/api/openapi.yaml b/api/openapi.yaml index 6a8024e01..a79e12c06 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -614,6 +614,22 @@ components: required: - name type: object + CreateWorkspaceInputBody: + additionalProperties: false + properties: + environment: + description: Free-form attribute policies can test + type: string + id: + description: Workspace ID, permanent for the workspace's life + type: string + name: + description: Display name + type: string + required: + - id + - name + type: object DeliveriesAttempt: additionalProperties: false properties: @@ -1121,6 +1137,98 @@ components: - model - answer type: object + GovernanceOrgBody: + additionalProperties: false + properties: + org: + $ref: "#/components/schemas/GovernanceOrgView" + required: + - org + type: object + GovernanceOrgEvent: + additionalProperties: false + properties: + actor_id: + type: string + actor_name: + type: string + at: + format: date-time + type: string + id: + format: int64 + type: integer + kind: + type: string + new_name: + type: string + old_name: + type: string + workspace_id: + type: string + required: + - id + - kind + - actor_id + - actor_name + - old_name + - new_name + - at + type: object + GovernanceOrgEventsBody: + additionalProperties: false + properties: + events: + items: + $ref: "#/components/schemas/GovernanceOrgEvent" + type: + - array + - "null" + required: + - events + type: object + GovernanceOrgView: + additionalProperties: false + properties: + id: + type: string + name: + type: string + role: + type: string + version: + format: int64 + type: integer + required: + - id + - name + - version + type: object + GovernanceOrgsBody: + additionalProperties: false + properties: + current: + type: string + instance_admin: + type: boolean + member_orgs: + items: + type: string + type: + - array + - "null" + orgs: + items: + $ref: "#/components/schemas/GovernanceOrgView" + type: + - array + - "null" + required: + - orgs + - current + - instance_admin + - member_orgs + type: object GovernancePasskey: additionalProperties: false properties: @@ -1329,6 +1437,46 @@ components: required: - user type: object + GovernanceWorkspace: + additionalProperties: false + properties: + environment: + type: string + id: + type: string + name: + type: string + org_id: + type: string + version: + format: int64 + type: integer + required: + - id + - org_id + - name + - version + type: object + GovernanceWorkspaceBody: + additionalProperties: false + properties: + workspace: + $ref: "#/components/schemas/GovernanceWorkspace" + required: + - workspace + type: object + GovernanceWorkspacesBody: + additionalProperties: false + properties: + workspaces: + items: + $ref: "#/components/schemas/GovernanceWorkspace" + type: + - array + - "null" + required: + - workspaces + type: object JudgementAction: additionalProperties: false properties: @@ -1886,6 +2034,20 @@ components: - code type: object RenameInputBody: + additionalProperties: false + properties: + expected_version: + description: The version the caller read, so a stale edit is refused + format: int64 + type: integer + name: + description: The new display name + type: string + required: + - name + - expected_version + type: object + RenameInputBody1: additionalProperties: false properties: title: @@ -1894,6 +2056,20 @@ components: required: - title type: object + RenameWorkspaceInputBody: + additionalProperties: false + properties: + expected_version: + description: The version the caller read, so a stale edit is refused + format: int64 + type: integer + name: + description: The new display name + type: string + required: + - name + - expected_version + type: object RunsActionTrail: additionalProperties: false properties: @@ -3073,7 +3249,7 @@ paths: content: application/json: schema: - $ref: "#/components/schemas/RenameInputBody" + $ref: "#/components/schemas/RenameInputBody1" required: true responses: "200": @@ -3993,6 +4169,219 @@ paths: summary: Accept an MCP server and the tools it may offer tags: - MCP servers + /api/orgs: + get: + operationId: list-orgs + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GovernanceOrgsBody" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: List the organisation the caller acts in + tags: + - Organisations + /api/orgs/{id}: + get: + operationId: get-org + parameters: + - description: Organisation ID + in: path + name: id + required: true + schema: + description: Organisation ID + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GovernanceOrgBody" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Get an organisation + tags: + - Organisations + patch: + operationId: rename-org + parameters: + - description: Organisation ID + in: path + name: id + required: true + schema: + description: Organisation ID + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/RenameInputBody" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GovernanceOrgBody" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Rename an organisation + tags: + - Organisations + /api/orgs/{id}/history: + get: + operationId: list-org-events + parameters: + - description: Organisation ID + in: path + name: id + required: true + schema: + description: Organisation ID + type: string + - description: How many changes to return, at most 200 + explode: false + in: query + name: limit + schema: + default: 50 + description: How many changes to return, at most 200 + format: int64 + type: integer + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GovernanceOrgEventsBody" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: List the organisation's name changes + tags: + - Organisations + /api/orgs/{id}/workspaces: + get: + operationId: list-org-workspaces + parameters: + - description: Organisation ID + in: path + name: id + required: true + schema: + description: Organisation ID + type: string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GovernanceWorkspacesBody" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: List an organisation's workspaces + tags: + - Organisations + post: + operationId: create-org-workspace + parameters: + - description: Organisation ID + in: path + name: id + required: true + schema: + description: Organisation ID + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/CreateWorkspaceInputBody" + required: true + responses: + "201": + content: + application/json: + schema: + $ref: "#/components/schemas/GovernanceWorkspaceBody" + description: Created + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Create a workspace + tags: + - Organisations + /api/orgs/{id}/workspaces/{workspace}: + patch: + operationId: rename-org-workspace + parameters: + - description: Organisation ID + in: path + name: id + required: true + schema: + description: Organisation ID + type: string + - description: Workspace ID + in: path + name: workspace + required: true + schema: + description: Workspace ID + type: string + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/RenameWorkspaceInputBody" + required: true + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/GovernanceWorkspaceBody" + description: OK + default: + content: + application/problem+json: + schema: + $ref: "#/components/schemas/ErrorModel" + description: Error + summary: Rename a workspace + tags: + - Organisations /api/people: get: operationId: list-people diff --git a/internal/app/archie/api.go b/internal/app/archie/api.go index bce4c83db..ada9455a5 100644 --- a/internal/app/archie/api.go +++ b/internal/app/archie/api.go @@ -41,6 +41,7 @@ type apiModules struct { func (m apiModules) register(api huma.API) { m.settings.Register(api) m.settings.RegisterAccounts(api) + m.settings.RegisterOrganisations(api) m.conns.Register(api) m.system.Register(api) m.tell.Register(api) diff --git a/internal/app/archie/run.go b/internal/app/archie/run.go index 30f42303e..07be029cf 100644 --- a/internal/app/archie/run.go +++ b/internal/app/archie/run.go @@ -115,6 +115,9 @@ func Run(ctx context.Context, configPath string) error { if err != nil { return err } + // Administrative writes are checked against the same live policy chain as + // every other request. + settings.UseAuthorizer(access) talk.Use(chat.Deps{People: settings, Access: access, Settings: settings, Toolbox: conns, Judge: judge, Approver: allow, Memory: remember, Runs: engine, Notifier: tell}) apiModules{ settings: settings, conns: conns, system: sys, tell: tell, allow: allow, classes: classes, policies: policies, diff --git a/internal/platform/pg/migrations/00039_governance_org_names.sql b/internal/platform/pg/migrations/00039_governance_org_names.sql new file mode 100644 index 000000000..1eaeb069f --- /dev/null +++ b/internal/platform/pg/migrations/00039_governance_org_names.sql @@ -0,0 +1,27 @@ +-- +goose Up +-- A name is a display label: changing it never changes an ID, so a rename is +-- an update guarded by the revision the caller read. +ALTER TABLE governance.orgs ADD COLUMN version bigint NOT NULL DEFAULT 1; +ALTER TABLE governance.workspaces ADD COLUMN version bigint NOT NULL DEFAULT 1; + +-- Every rename is appended here, with who made it and what the name was, so a +-- name change is attributable after the fact. +CREATE TABLE governance.org_events ( + id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + org_id text NOT NULL REFERENCES governance.orgs (id), + workspace_id text NOT NULL DEFAULT '', + event_type text NOT NULL, + actor_id text NOT NULL, + actor_name text NOT NULL, + request_id text NOT NULL UNIQUE, + old_name text NOT NULL, + new_name text NOT NULL, + at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX idx_governance_org_events_org_at + ON governance.org_events (org_id, at DESC, id DESC); + +-- +goose Down +DROP TABLE governance.org_events; +ALTER TABLE governance.workspaces DROP COLUMN version; +ALTER TABLE governance.orgs DROP COLUMN version; diff --git a/modules/governance/access.go b/modules/governance/access.go index fa96ff270..a2544c3e9 100644 --- a/modules/governance/access.go +++ b/modules/governance/access.go @@ -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 { diff --git a/modules/governance/accounts_api.go b/modules/governance/accounts_api.go index 0a556e5a4..b6d76cd0d 100644 --- a/modules/governance/accounts_api.go +++ b/modules/governance/accounts_api.go @@ -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 } diff --git a/modules/governance/governance.go b/modules/governance/governance.go index fc99cb6a3..1320f033d 100644 --- a/modules/governance/governance.go +++ b/modules/governance/governance.go @@ -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, "") diff --git a/modules/governance/internal/store/access.go b/modules/governance/internal/store/access.go index 73f0f9bf0..6373436ff 100644 --- a/modules/governance/internal/store/access.go +++ b/modules/governance/internal/store/access.go @@ -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. diff --git a/modules/governance/internal/store/orgs.go b/modules/governance/internal/store/orgs.go index ff2a18d1c..fc074a14e 100644 --- a/modules/governance/internal/store/orgs.go +++ b/modules/governance/internal/store/orgs.go @@ -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, ¤t, ` + 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, ¤t, ` + 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 { diff --git a/modules/governance/org.go b/modules/governance/org.go index a0044ee8d..214eb6957 100644 --- a/modules/governance/org.go +++ b/modules/governance/org.go @@ -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 diff --git a/modules/governance/org_test.go b/modules/governance/org_test.go new file mode 100644 index 000000000..bd7f68375 --- /dev/null +++ b/modules/governance/org_test.go @@ -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) + } + }) + } +} diff --git a/modules/governance/orgs_api.go b/modules/governance/orgs_api.go new file mode 100644 index 000000000..fbab14b3e --- /dev/null +++ b/modules/governance/orgs_api.go @@ -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 +} diff --git a/modules/governance/store_orgs.go b/modules/governance/store_orgs.go index 217b0be78..d402e6c53 100644 --- a/modules/governance/store_orgs.go +++ b/modules/governance/store_orgs.go @@ -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 { diff --git a/ui/src/App.vue b/ui/src/App.vue index ad6a95d2f..972d414ee 100644 --- a/ui/src/App.vue +++ b/ui/src/App.vue @@ -36,12 +36,20 @@ const route = useRoute(); const router = useRouter(); const workflowsPage = computed(() => route.name === "workflow"); const hidden = computed(() => hiddenPaths(session.sections)); +// The redirect below must not run during the router's first navigation: route +// is still the start location then, so a deep link would be replaced by the +// landing page before it resolves. +const routerReady = ref(false); +void router.isReady().then(() => { + routerReady.value = true; +}); const main = ref(null); const newTaskOpen = ref(false); // A page the caller may not open is not reachable by URL either: the nav drops // it, so a bookmark or a chat link must not land on a form whose saves the // control plane refuses. watch([() => route.path, hidden], () => { + if (!routerReady.value) return; if (!hidden.value.includes(typeof route.meta.navPath === "string" ? route.meta.navPath : route.path)) return; // Home may be hidden too, so land on the first destination that is served. const first = navTree(hidden.value).find((node) => node.kind === "link"); diff --git a/ui/src/copy/errors/org.ts b/ui/src/copy/errors/org.ts index b2b508527..bdce12224 100644 --- a/ui/src/copy/errors/org.ts +++ b/ui/src/copy/errors/org.ts @@ -2,4 +2,7 @@ export const org = { identities: { unavailable: "Unavailable identity", }, + rename: { + conflict: (name: string) => `The name is now “${name}”. Save again to replace it.`, + }, } as const; diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts index 509f83457..eae39e577 100644 --- a/ui/src/lib/api.ts +++ b/ui/src/lib/api.ts @@ -277,6 +277,10 @@ export const api = { orgCreate: (org: { id: string; name: string; owner_identity: string }) => request("/api/orgs", { method: "POST", body: org }), org: (id: string) => request(`/api/orgs/${encodeURIComponent(id)}`), + // renameOrg changes the org's display name; expected_version refuses a save + // made from a name someone else has since changed. + renameOrg: (id: string, change: { name: string; expected_version: number }) => + request(`/api/orgs/${encodeURIComponent(id)}`, { method: "PATCH", body: change }), orgWorkspaces: (id: string) => request(`/api/orgs/${encodeURIComponent(id)}/workspaces`), createOrgWorkspace: ( @@ -287,6 +291,18 @@ export const api = { method: "POST", body: workspace, }), + renameOrgWorkspace: ( + id: string, + workspace: string, + change: { name: string; expected_version: number }, + ) => + request( + `/api/orgs/${encodeURIComponent(id)}/workspaces/${encodeURIComponent(workspace)}`, + { method: "PATCH", body: change }, + ), + // orgHistory lists the org's appended name changes, newest first. + orgHistory: (id: string) => + request(`/api/orgs/${encodeURIComponent(id)}/history`), orgAgents: (id: string) => request(`/api/orgs/${encodeURIComponent(id)}/agents`), orgMembers: (id: string) => request(`/api/orgs/${encodeURIComponent(id)}/members`), diff --git a/ui/src/org/OrgOverviewPage.vue b/ui/src/org/OrgOverviewPage.vue index c955ce7c8..3154862a3 100644 --- a/ui/src/org/OrgOverviewPage.vue +++ b/ui/src/org/OrgOverviewPage.vue @@ -1,38 +1,129 @@ diff --git a/ui/src/org/OrgWorkspacesPage.vue b/ui/src/org/OrgWorkspacesPage.vue index d0946b9f3..f4fcf1955 100644 --- a/ui/src/org/OrgWorkspacesPage.vue +++ b/ui/src/org/OrgWorkspacesPage.vue @@ -3,10 +3,17 @@ import { Alert, AlertDescription } from "@/components/ui/alert"; import PageHeader from "@/base/PageHeader.vue"; import { Section } from "@/components/ui/section"; import { storeToRefs } from "pinia"; -import { onMounted, ref } from "vue"; -import { Plus } from "@lucide/vue"; +import { computed, onMounted, ref } from "vue"; +import { Pencil, Plus } from "@lucide/vue"; import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty"; import { Input } from "@/components/ui/input"; import { @@ -17,13 +24,14 @@ import { TableHeader, TableRow, } from "@/components/ui/table"; -import { api, describeError } from "@/lib/api"; +import { ApiError, api, describeError } from "@/lib/api"; import { errors } from "@/copy/errors"; import { useOrgStore } from "@/stores/org"; import type { OrgWorkspace } from "./org"; /** - * The org's workspaces: the division policies and records are scoped to. + * The org's workspaces: the division policies and records are scoped to. The + * name is a label, so an owner can correct it without moving anything. */ const orgStore = useOrgStore(); const { org } = storeToRefs(orgStore); @@ -35,6 +43,9 @@ const error = ref(""); const loading = ref(true); const busy = ref(false); +const canCreate = computed(() => org.value?.role === "owner" || org.value?.role === "admin"); +const canRename = computed(() => org.value?.role === "owner"); + async function load(): Promise { if (!org.value) return; try { @@ -78,6 +89,54 @@ async function create(): Promise { busy.value = false; } } + +const renaming = ref(null); +const draft = ref(""); +const renameError = ref(""); +const renameBusy = ref(false); + +function openRename(workspace: OrgWorkspace): void { + renaming.value = workspace; + draft.value = workspace.name; + renameError.value = ""; +} + +function closeRename(open: boolean): void { + if (!open) renaming.value = null; +} + +async function rename(): Promise { + const workspace = renaming.value; + const name = draft.value.trim(); + if (!org.value || !workspace || !name || renameBusy.value) return; + renameBusy.value = true; + renameError.value = ""; + try { + const updated = ( + await api.renameOrgWorkspace<{ workspace: OrgWorkspace }>( + org.value.id, + workspace.id, + { name, expected_version: workspace.version }, + ) + ).workspace; + const at = workspaces.value.findIndex((w) => w.id === updated.id); + if (at >= 0) workspaces.value[at] = updated; + renaming.value = null; + } catch (cause) { + if (cause instanceof ApiError && cause.status === 409) { + // Another tab changed it first. Reload so the current name and revision + // are on screen, keep the draft, and let the operator decide. + await load(); + const fresh = workspaces.value.find((w) => w.id === workspace.id); + if (fresh) renaming.value = fresh; + renameError.value = errors.org.rename.conflict(fresh?.name ?? workspace.name); + } else { + renameError.value = describeError(cause, errors.common.unknown); + } + } finally { + renameBusy.value = false; + } +} diff --git a/ui/src/org/org.ts b/ui/src/org/org.ts index 6be7dbe2b..6dfb616e4 100644 --- a/ui/src/org/org.ts +++ b/ui/src/org/org.ts @@ -1,14 +1,31 @@ -/** An org on the instance. A non-admin only ever sees their own. */ +/** An org the caller belongs to, with their own org-wide role. `version` is the + * revision a rename is guarded by. */ export interface Org { id: string; name: string; + version: number; + role?: Role; } +/** A workspace as the org's caller sees it. `version` guards a rename. */ export interface OrgWorkspace { id: string; org_id: string; name: string; environment?: string; + version: number; +} + +/** One appended name change: the organisation itself, or one of its workspaces. */ +export interface OrgEvent { + id: number; + kind: "org" | "workspace"; + workspace_id?: string; + actor_id: string; + actor_name: string; + old_name: string; + new_name: string; + at: string; } export type Role = "owner" | "admin" | "developer" | "viewer"; diff --git a/ui/src/stores/org.ts b/ui/src/stores/org.ts index 1977abe1f..453d3ced2 100644 --- a/ui/src/stores/org.ts +++ b/ui/src/stores/org.ts @@ -67,6 +67,20 @@ export const useOrgStore = defineStore("org", () => { org.value = orgs.value.find((o) => o.id === id) ?? org.value; } + /** renameOrg changes the open org's display name and keeps the shared list + * in step, so the breadcrumb and every tab show the name without a reload. */ + async function renameOrg(name: string): Promise { + const current = org.value; + if (!current) throw new Error("no organisation is open"); + const updated = (await api.renameOrg<{ org: Org }>(current.id, { + name, + expected_version: current.version, + })).org; + const at = orgs.value.findIndex((o) => o.id === updated.id); + if (at >= 0) orgs.value[at] = { ...orgs.value[at], ...updated }; + org.value = { ...current, ...updated }; + } + const identities = ref([]); /** True once the first identity read settled, so a list can wait without * showing its empty state. */ @@ -147,6 +161,7 @@ export const useOrgStore = defineStore("org", () => { org, loadOrg, viewOrg, + renameOrg, identities, identitiesLoaded, identitiesAvailable,