feat(org): org, workspace and membership API

This commit is contained in:
sam committed 2026-10-05 20:44:49 +11:00
1 parent 0788f5ab8a
commit fb05189e42
20 files changed
+2960 -271

No files matched your search

+221
View File
@@ -0,0 +1,221 @@
package webui
import (
"encoding/json"
"errors"
"net/http"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// orgReady answers Unavailable when this process hosts no org store.
func (s *Server) orgReady(w http.ResponseWriter) bool {
if s.Orgs == nil {
http.Error(w, "orgs unavailable", http.StatusServiceUnavailable)
return false
}
return true
}
// orgInPath resolves the route's {id}, requiring it to be the caller's own
// org: the dashboard has no instance-admin view yet, so a path that names
// another tenant reads as not found rather than leaking it.
func (s *Server) orgInPath(w http.ResponseWriter, r *http.Request) (org.OrgID, bool) {
caller := policyOrg(r)
if r.PathValue("id") != string(caller) {
http.Error(w, "org not found", http.StatusNotFound)
return "", false
}
return caller, true
}
// handleOrgsList lists the caller's org only. The State Store contract lists
// every org; instance-admin widening is a later change.
func (s *Server) handleOrgsList(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
return
}
values, err := s.Orgs.ListOrgs(r.Context())
if err != nil {
writeOrgError(w, err)
return
}
caller := policyOrg(r)
out := []org.Org{}
for _, value := range values {
if value.ID == caller {
out = append(out, value)
}
}
writeJSON(w, map[string]any{"orgs": out})
}
func (s *Server) handleOrgGet(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
return
}
id, ok := s.orgInPath(w, r)
if !ok {
return
}
value, err := s.Orgs.GetOrg(r.Context(), id)
if err != nil {
writeOrgError(w, err)
return
}
writeJSON(w, map[string]any{"org": value})
}
func (s *Server) handleOrgWorkspacesList(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
return
}
id, ok := s.orgInPath(w, r)
if !ok {
return
}
values, err := s.Orgs.ListWorkspaces(r.Context(), id)
if err != nil {
writeOrgError(w, err)
return
}
if values == nil {
values = []org.Workspace{}
}
writeJSON(w, map[string]any{"workspaces": values})
}
func (s *Server) handleOrgWorkspaceCreate(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
return
}
id, ok := s.orgInPath(w, r)
if !ok {
return
}
var request struct {
ID string `json:"id"`
Name string `json:"name"`
Environment string `json:"environment"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)).Decode(&request); err != nil {
http.Error(w, "invalid workspace: "+err.Error(), http.StatusBadRequest)
return
}
value, err := s.Orgs.CreateWorkspace(r.Context(), org.Workspace{
ID: org.WorkspaceID(request.ID), OrgID: id, Name: request.Name, Environment: request.Environment,
})
if err != nil {
writeOrgError(w, err)
return
}
w.WriteHeader(http.StatusCreated)
writeJSON(w, map[string]any{"workspace": value})
}
func (s *Server) handleOrgMembersList(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
return
}
id, ok := s.orgInPath(w, r)
if !ok {
return
}
values, err := s.Orgs.ListMembers(r.Context(), id)
if err != nil {
writeOrgError(w, err)
return
}
if values == nil {
values = []org.Member{}
}
writeJSON(w, map[string]any{"members": values})
}
// handleOrgMemberSet grants or moves one identity's role in the caller's org,
// or in one workspace when the body names one.
func (s *Server) handleOrgMemberSet(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
return
}
id, ok := s.orgInPath(w, r)
if !ok {
return
}
var request struct {
Role string `json:"role"`
Workspace string `json:"workspace"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10)).Decode(&request); err != nil {
http.Error(w, "invalid membership: "+err.Error(), http.StatusBadRequest)
return
}
membership := org.Membership{
IdentityID: identity.IdentityID(r.PathValue("identity")),
OrgID: id,
WorkspaceID: org.WorkspaceID(request.Workspace),
Role: org.Role(request.Role),
}
if err := s.Orgs.EnsureMembership(r.Context(), membership); err != nil {
writeOrgError(w, err)
return
}
writeJSON(w, map[string]any{"membership": membership})
}
func (s *Server) handleOrgMemberRemove(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
return
}
id, ok := s.orgInPath(w, r)
if !ok {
return
}
membership := org.Membership{
IdentityID: identity.IdentityID(r.PathValue("identity")),
OrgID: id,
WorkspaceID: org.WorkspaceID(r.URL.Query().Get("workspace")),
}
if err := s.Orgs.RemoveMembership(r.Context(), membership); err != nil {
writeOrgError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func (s *Server) handleOrgAgentAssign(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
return
}
id, ok := s.orgInPath(w, r)
if !ok {
return
}
err := s.Orgs.AssignAgent(r.Context(), org.AgentAssignment{
IdentityID: identity.IdentityID(r.PathValue("identity")), OrgID: id,
})
if err != nil {
writeOrgError(w, err)
return
}
writeJSON(w, map[string]any{"assigned": true})
}
// writeOrgError maps the org domain's errors, and their gRPC statuses, onto
// HTTP. The remote-client path keeps the status code through unmapError's
// wrapping, so writeControlPlaneError names the same code the store sent.
func writeOrgError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, org.ErrInvalidRole), errors.Is(err, org.ErrInvalidOrg),
errors.Is(err, org.ErrInvalidMembership), errors.Is(err, org.ErrInvalidWorkspace),
errors.Is(err, org.ErrInvalidAssignment):
http.Error(w, err.Error(), http.StatusBadRequest)
case errors.Is(err, org.ErrOrgNotFound):
http.Error(w, err.Error(), http.StatusNotFound)
case errors.Is(err, org.ErrOrgExists), errors.Is(err, org.ErrWorkspaceExists), errors.Is(err, org.ErrMembershipExists):
http.Error(w, err.Error(), http.StatusConflict)
default:
writeControlPlaneError(w, err)
}
}
+155
View File
@@ -0,0 +1,155 @@
package webui
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// fakeOrgs is an in-memory org.API that validates memberships the way the
// store does.
type fakeOrgs struct {
orgs []org.Org
workspaces map[org.OrgID][]org.Workspace
members map[org.OrgID][]org.Member
agents []org.AgentAssignment
}
func newFakeOrgs() *fakeOrgs {
return &fakeOrgs{
orgs: []org.Org{{ID: org.DefaultOrgID, Name: "System"}},
workspaces: map[org.OrgID][]org.Workspace{},
members: map[org.OrgID][]org.Member{
org.DefaultOrgID: {{IdentityID: "seed", Kind: identity.KindUser, DisplayName: "Seed", Role: org.RoleDeveloper}},
},
}
}
func (f *fakeOrgs) ListOrgs(context.Context) ([]org.Org, error) { return f.orgs, nil }
func (f *fakeOrgs) GetOrg(_ context.Context, id org.OrgID) (org.Org, error) {
for _, o := range f.orgs {
if o.ID == id {
return o, nil
}
}
return org.Org{}, org.ErrOrgNotFound
}
func (f *fakeOrgs) ListWorkspaces(_ context.Context, id org.OrgID) ([]org.Workspace, error) {
return f.workspaces[id], nil
}
func (f *fakeOrgs) CreateWorkspace(_ context.Context, value org.Workspace) (org.Workspace, error) {
if err := value.Validate(); err != nil {
return org.Workspace{}, err
}
f.workspaces[value.OrgID] = append(f.workspaces[value.OrgID], value)
return value, nil
}
func (f *fakeOrgs) ListMembers(_ context.Context, id org.OrgID) ([]org.Member, error) {
return f.members[id], nil
}
func (f *fakeOrgs) EnsureMembership(_ context.Context, value org.Membership) error {
if err := value.Validate(); err != nil {
return err
}
list := f.members[value.OrgID]
for i := range list {
if list[i].IdentityID == value.IdentityID && list[i].WorkspaceID == value.WorkspaceID {
list[i].Role = value.Role
return nil
}
}
f.members[value.OrgID] = append(list, org.Member{IdentityID: value.IdentityID, WorkspaceID: value.WorkspaceID, Role: value.Role})
return nil
}
func (f *fakeOrgs) RemoveMembership(_ context.Context, value org.Membership) error {
kept := f.members[value.OrgID][:0]
for _, m := range f.members[value.OrgID] {
if m.IdentityID == value.IdentityID && m.WorkspaceID == value.WorkspaceID {
continue
}
kept = append(kept, m)
}
f.members[value.OrgID] = kept
return nil
}
func (f *fakeOrgs) AssignAgent(_ context.Context, value org.AgentAssignment) error {
f.agents = append(f.agents, value)
return nil
}
// orgRoutes is the org mux behind the same credential and authorize wrappers
// the real server mounts.
func orgRoutes(s *Server) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /api/orgs", s.handleOrgsList)
mux.HandleFunc("GET /api/orgs/{id}", s.handleOrgGet)
mux.HandleFunc("GET /api/orgs/{id}/workspaces", s.handleOrgWorkspacesList)
mux.HandleFunc("POST /api/orgs/{id}/workspaces", s.handleOrgWorkspaceCreate)
mux.HandleFunc("GET /api/orgs/{id}/members", s.handleOrgMembersList)
mux.HandleFunc("PUT /api/orgs/{id}/members/{identity}", s.handleOrgMemberSet)
mux.HandleFunc("DELETE /api/orgs/{id}/members/{identity}", s.handleOrgMemberRemove)
mux.HandleFunc("PUT /api/orgs/{id}/agents/{identity}", s.handleOrgAgentAssign)
return s.requireToken(s.authorize(mux))
}
// TestOrgRoutes drives the dashboard's org API through its HTTP handlers: the
// shared-token session lists its own org, its workspaces and members, adds a
// membership, changes its role and removes it, and an unknown role is refused
// naming the role.
func TestOrgRoutes(t *testing.T) {
tests := []struct {
name string
method string
path string
body string
wantStatus int
wantBody string
}{
{"lists the caller's org", http.MethodGet, "/api/orgs", "", http.StatusOK, string(org.DefaultOrgID)},
{"another org reads as not found", http.MethodGet, "/api/orgs/other", "", http.StatusNotFound, ""},
{"reads the caller's org", http.MethodGet, "/api/orgs/" + string(org.DefaultOrgID), "", http.StatusOK, "System"},
{"lists workspaces", http.MethodGet, "/api/orgs/" + string(org.DefaultOrgID) + "/workspaces", "", http.StatusOK, "workspaces"},
{"creates a workspace", http.MethodPost, "/api/orgs/" + string(org.DefaultOrgID) + "/workspaces", `{"id":"ops","name":"Ops"}`, http.StatusCreated, "ops"},
{"lists members", http.MethodGet, "/api/orgs/" + string(org.DefaultOrgID) + "/members", "", http.StatusOK, "seed"},
{"adds a membership", http.MethodPut, "/api/orgs/" + string(org.DefaultOrgID) + "/members/sam", `{"role":"developer"}`, http.StatusOK, "developer"},
{"changes a membership's role", http.MethodPut, "/api/orgs/" + string(org.DefaultOrgID) + "/members/seed", `{"role":"admin"}`, http.StatusOK, "admin"},
{"removes a membership", http.MethodDelete, "/api/orgs/" + string(org.DefaultOrgID) + "/members/seed", "", http.StatusNoContent, ""},
{"assigns an agent", http.MethodPut, "/api/orgs/" + string(org.DefaultOrgID) + "/agents/bot", "", http.StatusOK, "true"},
{"an unknown role is refused naming it", http.MethodPut, "/api/orgs/" + string(org.DefaultOrgID) + "/members/sam", `{"role":"superuser"}`, http.StatusBadRequest, "superuser"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &Server{Token: "shared", Access: allowAll{}, Principals: stubPrincipals(true), Orgs: newFakeOrgs()}
var body io.Reader
if tt.body != "" {
body = strings.NewReader(tt.body)
}
req := httptest.NewRequestWithContext(t.Context(), tt.method, tt.path, body)
req.Header.Set("Authorization", "Bearer shared")
if tt.body != "" {
req.Header.Set("Content-Type", "application/json")
}
rec := httptest.NewRecorder()
orgRoutes(s).ServeHTTP(rec, req)
if rec.Code != tt.wantStatus {
t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String())
}
if tt.wantBody != "" && !strings.Contains(rec.Body.String(), tt.wantBody) {
t.Fatalf("body = %s, want it to contain %q", rec.Body.String(), tt.wantBody)
}
})
}
}
+22 -4
View File
@@ -136,6 +136,8 @@ func routeOverride(action access.Action, path string) (access.Action, access.Res
return policyAction(action), access.KindPolicy, "", true
case matchPrefix(path, "/api/identities"):
return actionManage(action), access.KindIdentity, segmentValue(path, 2), true
case matchPrefix(path, "/api/orgs"):
return orgRouteAction(action), access.KindOrg, segmentValue(path, 2), true
case matchPrefix(path, "/api/extensions"):
// Installing and enabling an extension runs a process on the host, so it
// is the same administration as editing a control-plane resource.
@@ -143,10 +145,7 @@ func routeOverride(action access.Action, path string) (access.Action, access.Res
case matchPrefix(path, "/api/control-plane/resources"):
return actionManage(action), access.KindPolicy, segmentValue(path, 3), true
case matchPrefix(path, "/api/chat"):
if action == access.ActionCreate {
return access.ActionRun, access.KindWorkflow, "", true
}
return access.ActionRead, access.KindDashboard, "", true
return chatRoute(action)
case matchSegment(path, "/api/sources/", "/secret"):
return access.ActionUpdate, access.KindSecret, segmentValue(path, 2), true
case matchPrefix(path, "/api/harness/terminal"):
@@ -179,6 +178,25 @@ func bindingCommand(action access.Action, path string) (access.Action, bool) {
return action, false
}
// orgRouteAction maps an org request: reads are org reads, and every mutation
// of the org's workspaces, members or agents is an update of the org itself,
// so the read/edit role policies decide it.
func orgRouteAction(action access.Action) access.Action {
if action == access.ActionRead {
return access.ActionRead
}
return access.ActionUpdate
}
// chatRoute maps a chat request: posting runs a workflow, anything else reads
// the dashboard.
func chatRoute(action access.Action) (access.Action, access.ResourceKind, string, bool) {
if action == access.ActionCreate {
return access.ActionRun, access.KindWorkflow, "", true
}
return access.ActionRead, access.KindDashboard, "", true
}
// kindOf maps a collection route onto the resource kind it addresses.
func kindOf(path string) access.ResourceKind {
switch {
+13
View File
@@ -15,6 +15,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/storepkg"
"github.com/samcharles93/archie-core/internal/events"
@@ -126,6 +127,10 @@ type Server struct {
Principals access.PrincipalSource
Denials access.DenialRecorder
// Orgs serves the org pages: the caller's org, its workspaces, members and
// agent assignments. Nil answers the org routes Unavailable.
Orgs org.API
// Events publishes operator actions so they reach the task timeline and
// the live activity stream. Optional: nil means the action is recorded
// in the store but invisible to anyone watching.
@@ -323,6 +328,14 @@ func (s *Server) registerConfigAndLogRoutes(mux *http.ServeMux) {
mux.HandleFunc("POST /api/control-plane/resources/{kind}/commands/{command}", s.handleControlPlaneCommand)
mux.HandleFunc("GET /api/control-plane/audit", s.handleAudit)
mux.HandleFunc("GET /api/identities", s.handleIdentitiesList)
mux.HandleFunc("GET /api/orgs", s.handleOrgsList)
mux.HandleFunc("GET /api/orgs/{id}", s.handleOrgGet)
mux.HandleFunc("GET /api/orgs/{id}/workspaces", s.handleOrgWorkspacesList)
mux.HandleFunc("POST /api/orgs/{id}/workspaces", s.handleOrgWorkspaceCreate)
mux.HandleFunc("GET /api/orgs/{id}/members", s.handleOrgMembersList)
mux.HandleFunc("PUT /api/orgs/{id}/members/{identity}", s.handleOrgMemberSet)
mux.HandleFunc("DELETE /api/orgs/{id}/members/{identity}", s.handleOrgMemberRemove)
mux.HandleFunc("PUT /api/orgs/{id}/agents/{identity}", s.handleOrgAgentAssign)
mux.HandleFunc("GET /api/tokens", s.handlePersonalTokensList)
mux.HandleFunc("POST /api/tokens", s.handlePersonalTokenCreate)
mux.HandleFunc("DELETE /api/tokens/{id}", s.handlePersonalTokenRevoke)