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:
1 parent
2cf9d435cc
commit
2fb0084d2c
17 files changed
+356
-69
No files matched your search
@@ -396,7 +396,8 @@ func (b *server) runCredentials(ctx context.Context) (*staterpc.TaskGrants, erro
|
||||
// store's principals.
|
||||
func (b *server) callers() rpcidentity.Callers {
|
||||
ps, _ := b.st.(access.PrincipalSource)
|
||||
return rpcidentity.Callers{Principals: ps}
|
||||
workspaces, _ := b.st.(access.WorkspaceLister)
|
||||
return rpcidentity.Callers{Principals: ps, Workspaces: workspaces}
|
||||
}
|
||||
|
||||
// accessDeps wires the policy chain and its denial records from the same
|
||||
|
||||
@@ -2,6 +2,7 @@ package access
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
@@ -98,6 +99,46 @@ func (p Principal) InstanceAdmin() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// ErrNotMember refuses selecting an org the principal holds no membership in.
|
||||
var ErrNotMember = errors.New("not a member of that org")
|
||||
|
||||
// WorkspaceLister reads an org's workspaces.
|
||||
type WorkspaceLister interface {
|
||||
ListWorkspaces(context.Context, org.OrgID) ([]org.Workspace, error)
|
||||
}
|
||||
|
||||
// Select returns the principal acting in org id, which it must hold a
|
||||
// membership in. Selecting the org it already serves needs no lookup. Every
|
||||
// authority that honours a caller's chosen org goes through here, so the
|
||||
// membership check is the single gate.
|
||||
func (p Principal) Select(ctx context.Context, id org.OrgID, workspaces WorkspaceLister) (Principal, error) {
|
||||
if id == "" || id == p.Org {
|
||||
return p, nil
|
||||
}
|
||||
if !p.Member(id) {
|
||||
return Principal{}, ErrNotMember
|
||||
}
|
||||
if workspaces == nil {
|
||||
return Principal{}, errors.New("org selection unavailable")
|
||||
}
|
||||
list, err := workspaces.ListWorkspaces(ctx, id)
|
||||
if err != nil {
|
||||
return Principal{}, err
|
||||
}
|
||||
p.Org, p.Workspaces = id, list
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// Member reports whether the principal holds any membership in org id.
|
||||
func (p Principal) Member(id org.OrgID) bool {
|
||||
for _, m := range p.Memberships {
|
||||
if m.OrgID == id {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Resource is the record acted on: its type, its workspace and org as
|
||||
// parents, its owner and its state.
|
||||
type Resource struct {
|
||||
|
||||
@@ -3,6 +3,7 @@ package rpcidentity
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
@@ -23,14 +24,22 @@ const CallerKey = "state-store-caller"
|
||||
// for one.
|
||||
const PrincipalKey = "state-store-principal"
|
||||
|
||||
// OrgKey carries the org the principal acts in, which differs from the one it
|
||||
// serves when the caller selected another org it is a member of.
|
||||
const OrgKey = "state-store-org"
|
||||
|
||||
// Outgoing forwards the context's principal, replacing any stale attribution.
|
||||
func Outgoing(ctx context.Context, caller string) context.Context {
|
||||
md, _ := metadata.FromOutgoingContext(ctx)
|
||||
md = md.Copy()
|
||||
md.Set(CallerKey, caller)
|
||||
md.Delete(PrincipalKey)
|
||||
md.Delete(OrgKey)
|
||||
if p, ok := access.PrincipalFromContext(ctx); ok {
|
||||
md.Set(PrincipalKey, string(p.IdentityID))
|
||||
if p.Org != "" {
|
||||
md.Set(OrgKey, string(p.Org))
|
||||
}
|
||||
}
|
||||
return metadata.NewOutgoingContext(ctx, md)
|
||||
}
|
||||
@@ -42,6 +51,9 @@ func Outgoing(ctx context.Context, caller string) context.Context {
|
||||
// org; any other acts in the default org.
|
||||
type Callers struct {
|
||||
Principals access.PrincipalSource
|
||||
// Workspaces lets a call act in an org it selected; without it any
|
||||
// selection other than the principal's own org is refused.
|
||||
Workspaces access.WorkspaceLister
|
||||
}
|
||||
|
||||
func (c Callers) resolve(ctx context.Context) (context.Context, error) {
|
||||
@@ -67,6 +79,15 @@ func (c Callers) resolve(ctx context.Context) (context.Context, error) {
|
||||
if err != nil {
|
||||
return nil, status.Errorf(codes.Unavailable, "resolve principal: %v", err)
|
||||
}
|
||||
// The forwarded org is a claim: the membership check, not the metadata,
|
||||
// decides whether the call may act there.
|
||||
p, err = p.Select(ctx, org.OrgID(first(md, OrgKey)), c.Workspaces)
|
||||
if err != nil {
|
||||
if errors.Is(err, access.ErrNotMember) {
|
||||
return nil, status.Error(codes.PermissionDenied, err.Error())
|
||||
}
|
||||
return nil, status.Errorf(codes.Unavailable, "select org: %v", err)
|
||||
}
|
||||
ctx = org.WithScope(org.WithOrg(access.WithActor(access.WithPrincipal(ctx, p), id), p.Org), p.Org)
|
||||
return ctx, nil
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ func (credentials) DeleteExpiredRunCredentials(context.Context, time.Time) error
|
||||
type principalsByID map[identity.IdentityID]org.OrgID
|
||||
|
||||
func (p principalsByID) PrincipalFor(_ context.Context, id identity.IdentityID) (access.Principal, error) {
|
||||
return access.Principal{IdentityID: id, Org: p[id]}, nil
|
||||
return access.Principal{IdentityID: id, Org: p[id], Memberships: []org.Membership{{IdentityID: id, OrgID: p[id], Role: org.RoleDeveloper}}}, nil
|
||||
}
|
||||
|
||||
// TestCallerAttribution pins who a call acts as: a trusted service's
|
||||
@@ -73,6 +73,8 @@ func TestCallerAttribution(t *testing.T) {
|
||||
}{
|
||||
{"service alone acts in the default org", plaintext, []string{rpcidentity.CallerKey, "archied"}, "archied", org.DefaultOrgID, false},
|
||||
{"forwarded principal sets actor and org", plaintext, []string{rpcidentity.CallerKey, "archie-ui", rpcidentity.PrincipalKey, "alice"}, "alice", "acme", false},
|
||||
{"forwarded org the principal serves is accepted", plaintext, []string{rpcidentity.CallerKey, "archie-ui", rpcidentity.PrincipalKey, "alice", rpcidentity.OrgKey, "acme"}, "alice", "acme", false},
|
||||
{"forwarded org the principal is not a member of is refused", plaintext, []string{rpcidentity.CallerKey, "archie-ui", rpcidentity.PrincipalKey, "alice", rpcidentity.OrgKey, "other"}, "", "", true},
|
||||
{"task grant cannot claim a principal", noCert, []string{tokenMetadataKey, taskToken, rpcidentity.CallerKey, "archie-ui", rpcidentity.PrincipalKey, "alice"}, "task/7", org.DefaultOrgID, false},
|
||||
{"no certificate and no grant is refused", noCert, []string{rpcidentity.CallerKey, "archied"}, "", "", true},
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user