feat(webui): act in a selected organisation the caller is a member of, enforced at the dashboard and the State Store

This commit is contained in:
sam committed 2026-10-27 11:06:18 +11:00
1 parent 2cf9d435cc
commit 2fb0084d2c
17 files changed
+356 -69

No files matched your search

+9 -4
View File
@@ -33,7 +33,8 @@ func (s *Server) orgInPath(w http.ResponseWriter, r *http.Request) (org.OrgID, b
}
// handleOrgsList lists every org to an instance admin and the caller's own
// to anyone else, naming the caller's org and whether it may switch.
// and member orgs to anyone else, naming the org the caller acts in and the
// ones it may select.
func (s *Server) handleOrgsList(w http.ResponseWriter, r *http.Request) {
if !s.orgReady(w) {
return
@@ -44,13 +45,17 @@ func (s *Server) handleOrgsList(w http.ResponseWriter, r *http.Request) {
return
}
caller, admin := policyOrg(r), instanceOwner(r)
out := []org.Org{}
principal, _ := access.PrincipalFromContext(r.Context())
out, member := []org.Org{}, []org.OrgID{}
for _, value := range values {
if value.ID == caller || admin {
if value.ID == caller || admin || principal.Member(value.ID) {
out = append(out, value)
}
if value.ID == caller || principal.Member(value.ID) {
member = append(member, value.ID)
}
}
writeJSON(w, map[string]any{"orgs": out, "current": caller, "instance_admin": admin})
writeJSON(w, map[string]any{"orgs": out, "current": caller, "instance_admin": admin, "member_orgs": member})
}
// handleOrgCreate creates an org with its default workspace and first owner.
+75
View File
@@ -108,6 +108,7 @@ func orgRoutes(s *Server) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /api/orgs", s.handleOrgsList)
mux.HandleFunc("POST /api/orgs", s.handleOrgCreate)
mux.HandleFunc("PUT /api/orgs/current", s.handleOrgSelect)
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)
@@ -424,3 +425,77 @@ func TestOrgMemberAdd(t *testing.T) {
})
}
}
// memberPrincipals gives every identity memberships in org-sys and acme but
// not beta.
type memberPrincipals struct{}
func (memberPrincipals) PrincipalFor(_ context.Context, id identity.IdentityID) (access.Principal, error) {
return access.Principal{IdentityID: id, Org: org.DefaultOrgID, Memberships: []org.Membership{
{IdentityID: id, OrgID: org.DefaultOrgID, Role: org.RoleDeveloper},
{IdentityID: id, OrgID: "acme", Role: org.RoleDeveloper},
}}, nil
}
// TestOrgSelection holds the selection boundary: a caller acts in another org
// only when it is a member, whether it asks by selecting or by presenting an
// old cookie, and the server answers with the org it really acts in.
func TestOrgSelection(t *testing.T) {
tests := []struct {
name string
method string
path string
body string
cookie string
wantStatus int
wantCookie string // value of the org cookie the response sets, "-" for none
wantBody string
}{
{"selects a member org", http.MethodPut, "/api/orgs/current", `{"id":"acme"}`, "", http.StatusNoContent, "acme", ""},
{"refuses an org it is not a member of", http.MethodPut, "/api/orgs/current", `{"id":"beta"}`, "", http.StatusForbidden, "-", ""},
{"acts in the selected org", http.MethodGet, "/api/orgs", "", "acme", http.StatusOK, "-", `"current":"acme"`},
{"ignores and clears a cookie for a non-member org", http.MethodGet, "/api/orgs", "", "beta", http.StatusOK, "", `"current":"org-sys"`},
{"lists only the orgs it may select", http.MethodGet, "/api/orgs", "", "", http.StatusOK, "-", `"member_orgs":["org-sys","acme"]`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
orgs := newFakeOrgs()
orgs.orgs = append(orgs.orgs, org.Org{ID: "acme"}, org.Org{ID: "beta"})
s := &Server{
Access: allowAll{}, Principals: memberPrincipals{}, Orgs: orgs,
Authenticate: func(_ context.Context, token string) (identity.Identity, error) {
return identity.Identity{ID: identity.IdentityID(token), Kind: identity.KindUser}, nil
},
}
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 dev")
if tt.body != "" {
req.Header.Set("Content-Type", "application/json")
}
if tt.cookie != "" {
req.AddCookie(&http.Cookie{Name: s.cookies().org, Value: tt.cookie})
}
rec := httptest.NewRecorder()
orgRoutes(s).ServeHTTP(rec, req)
if rec.Code != tt.wantStatus {
t.Fatalf("status = %d, body %s", rec.Code, rec.Body.String())
}
set := "-"
for _, c := range rec.Result().Cookies() {
if c.Name == s.cookies().org {
set = c.Value
}
}
if set != tt.wantCookie {
t.Fatalf("org cookie = %q, want %q", set, tt.wantCookie)
}
if !strings.Contains(rec.Body.String(), tt.wantBody) {
t.Fatalf("body = %s, want it to contain %q", rec.Body.String(), tt.wantBody)
}
})
}
}
+8
View File
@@ -37,6 +37,10 @@ func (s *Server) authorize(h http.Handler) http.Handler {
http.Error(w, "principal unavailable", http.StatusServiceUnavailable)
return
}
if principal, err = s.selectedOrg(w, r, principal); err != nil {
http.Error(w, "principal unavailable", http.StatusServiceUnavailable)
return
}
action, kind, id := accessRequest(r)
ctx := org.WithOrg(access.WithPrincipal(r.Context(), principal), principal.Org)
// The record's org is not loaded here: org-filtered lookups keep a
@@ -455,6 +459,10 @@ func accountRoute(path string) (access.Action, access.ResourceKind, bool) {
switch path {
case "/api/accounts":
return access.ActionManageMembers, access.KindMember, true
case "/api/orgs/current":
// Choosing an org is open to any member; the handler checks the
// membership.
return access.ActionRead, access.KindDashboard, true
case "/api/authentication":
return access.ActionManageIdentities, access.KindIdentity, true
}
+2 -1
View File
@@ -6,7 +6,7 @@ import "strings"
// and ignore the port, so each name carries the instance: two instances on
// one host would otherwise overwrite each other's sessions.
type cookieNames struct {
token, account, providerToken, loginState, loginVerifier, passkeyRegistration, passkeyLogin string
token, account, providerToken, loginState, loginVerifier, passkeyRegistration, passkeyLogin, org string
}
func newCookieNames(instance string) cookieNames {
@@ -22,6 +22,7 @@ func newCookieNames(instance string) cookieNames {
loginVerifier: prefix + "_login_verifier",
passkeyRegistration: prefix + "_passkey_registration",
passkeyLogin: prefix + "_passkey_login",
org: prefix + "_org",
}
}
+71
View File
@@ -0,0 +1,71 @@
package webui
import (
"errors"
"net/http"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/org"
)
const orgCookieMaxAge = 365 * 24 * 60 * 60
// selectedOrg is the principal acting in the org the caller's cookie names. A
// selection the caller is not a member of is dropped, so a stale cookie falls
// back to the org the caller serves rather than locking it out.
func (s *Server) selectedOrg(w http.ResponseWriter, r *http.Request, principal access.Principal) (access.Principal, error) {
var chosen string
if cookie, err := r.Cookie(s.cookies().org); err == nil {
chosen = cookie.Value
}
if chosen == "" {
return principal, nil
}
selected, err := principal.Select(r.Context(), org.OrgID(chosen), s.workspaces())
if errors.Is(err, access.ErrNotMember) {
s.setOrgCookie(w, r, "")
return principal, nil
}
return selected, err
}
// workspaces is nil, not a typed nil, when no org store is wired.
func (s *Server) workspaces() access.WorkspaceLister {
if s.Orgs == nil {
return nil
}
return s.Orgs
}
func (s *Server) setOrgCookie(w http.ResponseWriter, r *http.Request, id string) {
cookie := &http.Cookie{
Name: s.cookies().org, Value: id, Path: "/",
HttpOnly: true, SameSite: http.SameSiteStrictMode, Secure: r.TLS != nil, MaxAge: orgCookieMaxAge,
}
if id == "" {
cookie.MaxAge = -1
}
http.SetCookie(w, cookie)
}
// handleOrgSelect makes the caller's chosen org the one its tasks, workflows
// and settings act in. Only an org the caller is a member of may be chosen.
func (s *Server) handleOrgSelect(w http.ResponseWriter, r *http.Request) {
request, ok := decodeBody[struct {
ID string `json:"id"`
}](w, r)
if !ok {
return
}
principal, _ := access.PrincipalFromContext(r.Context())
if _, err := principal.Select(r.Context(), org.OrgID(request.ID), s.workspaces()); err != nil {
if errors.Is(err, access.ErrNotMember) {
http.Error(w, "not a member of that org", http.StatusForbidden)
return
}
writeOrgError(w, err)
return
}
s.setOrgCookie(w, r, request.ID)
w.WriteHeader(http.StatusNoContent)
}
+1
View File
@@ -381,6 +381,7 @@ func (s *Server) registerConfigAndLogRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/identities", instanceOnly(s.handleIdentitiesList))
mux.HandleFunc("GET /api/orgs", s.handleOrgsList)
mux.HandleFunc("POST /api/orgs", s.handleOrgCreate)
mux.HandleFunc("PUT /api/orgs/current", s.handleOrgSelect)
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)