Files

522 lines
21 KiB
Go

package webui
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
)
// 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) CreateOrg(_ context.Context, value org.Org, owner identity.IdentityID) (org.Org, error) {
if err := value.Validate(); err != nil {
return org.Org{}, err
}
f.orgs = append(f.orgs, value)
f.members[value.ID] = []org.Member{{IdentityID: owner, Role: org.RoleOwner}}
return value, 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
}
// ListWorkspaces answers as the State Store does: the org asked for only to a
// caller who is a member of it, otherwise the caller's own org, and the
// system org when the call carries no principal.
func (f *fakeOrgs) ListWorkspaces(ctx context.Context, id org.OrgID) ([]org.Workspace, error) {
p, ok := access.PrincipalFromContext(ctx)
switch {
case !ok:
id = org.DefaultOrgID
case !p.Member(id):
id = p.Org
}
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()
newOrgsAPI(s).register(mux)
mux.HandleFunc("PUT /api/orgs/current", s.handleOrgSelect)
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)
}
})
}
}
// rolePrincipals gives each identity id the org-sys role of the same name.
type rolePrincipals struct{}
func (rolePrincipals) 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.Role(id)},
}}, nil
}
// TestOrgMembershipNeedsItsRole holds membership changes to the shipped role
// policies: a developer manages no members, an admin manages members but can
// neither grant the owner role nor change an owner's, and an owner can.
func TestOrgMembershipNeedsItsRole(t *testing.T) {
engine := infraaccess.New(access.ShippedOrgPolicies(org.DefaultOrgID))
members := "/api/orgs/" + string(org.DefaultOrgID) + "/members/"
tests := []struct {
name string
caller string
method string
path string
body string
wantStatus int
}{
{"a developer cannot add a member", "developer", http.MethodPut, members + "sam", `{"role":"viewer"}`, http.StatusForbidden},
{"a developer cannot make itself owner", "developer", http.MethodPut, members + "developer", `{"role":"owner"}`, http.StatusForbidden},
{"an admin adds a member", "admin", http.MethodPut, members + "sam", `{"role":"developer"}`, http.StatusOK},
{"an admin cannot make itself owner", "admin", http.MethodPut, members + "admin", `{"role":"owner"}`, http.StatusForbidden},
{"an admin cannot demote an owner", "admin", http.MethodPut, members + "boss", `{"role":"viewer"}`, http.StatusForbidden},
{"an admin cannot remove an owner", "admin", http.MethodDelete, members + "boss", "", http.StatusForbidden},
{"an owner grants owner", "owner", http.MethodPut, members + "sam", `{"role":"owner"}`, http.StatusOK},
{"a developer cannot assign an agent", "developer", http.MethodPut, "/api/orgs/" + string(org.DefaultOrgID) + "/agents/bot", "", http.StatusForbidden},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
orgs := newFakeOrgs()
orgs.members[org.DefaultOrgID] = append(orgs.members[org.DefaultOrgID], org.Member{IdentityID: "boss", Role: org.RoleOwner})
s := &Server{
Access: engine, Principals: rolePrincipals{}, 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 "+tt.caller)
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, want %d, body %s", rec.Code, tt.wantStatus, rec.Body.String())
}
})
}
}
// TestInstanceAdminOrgs holds the instance-admin boundary: an owner of org-sys
// lists and opens every org and creates one with its owner; an admin of
// org-sys sees only its own org and cannot create one.
func TestInstanceAdminOrgs(t *testing.T) {
engine := infraaccess.New(access.ShippedOrgPolicies(org.DefaultOrgID))
tests := []struct {
name string
caller string
method string
path string
body string
wantStatus int
wantBody string
}{
{"an instance admin lists every org", "owner", http.MethodGet, "/api/orgs", "", http.StatusOK, "acme"},
{"anyone else lists only their own", "admin", http.MethodGet, "/api/orgs", "", http.StatusOK, string(org.DefaultOrgID)},
{"an instance admin opens another org", "owner", http.MethodGet, "/api/orgs/acme/members", "", http.StatusOK, "boss"},
{"anyone else does not", "admin", http.MethodGet, "/api/orgs/acme/members", "", http.StatusNotFound, ""},
{"an instance admin creates an org with its owner", "owner", http.MethodPost, "/api/orgs", `{"id":"beta","name":"Beta","owner_identity":"sam"}`, http.StatusCreated, "beta"},
{"anyone else cannot", "admin", http.MethodPost, "/api/orgs", `{"id":"beta","name":"Beta","owner_identity":"sam"}`, http.StatusForbidden, ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
orgs := newFakeOrgs()
orgs.orgs = append(orgs.orgs, org.Org{ID: "acme", Name: "Acme"})
orgs.members["acme"] = []org.Member{{IdentityID: "boss", Role: org.RoleOwner}}
s := &Server{
Access: engine, Principals: rolePrincipals{}, 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 "+tt.caller)
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, want %d, body %s", rec.Code, tt.wantStatus, rec.Body.String())
}
if tt.wantBody != "" && !strings.Contains(rec.Body.String(), tt.wantBody) {
t.Fatalf("body = %s, want %q", rec.Body.String(), tt.wantBody)
}
if tt.caller == "admin" && tt.path == "/api/orgs" && strings.Contains(rec.Body.String(), "acme") {
t.Fatalf("a non-admin saw another org: %s", rec.Body.String())
}
})
}
}
// fakeSubjects is an in-memory identity store with subject bindings.
type fakeSubjects struct {
identity.Repository
byID map[identity.IdentityID]identity.Identity
bindings map[identity.Subject]identity.IdentityID
}
func (f *fakeSubjects) Create(_ context.Context, v identity.Identity, _ identity.Audit) (identity.Identity, error) {
f.byID[v.ID] = v
return v, nil
}
func (f *fakeSubjects) ResolveSubject(_ context.Context, s identity.Subject) (identity.Identity, error) {
if id, ok := f.bindings[s]; ok {
return f.byID[id], nil
}
return identity.Identity{}, identity.ErrNotFound
}
func (f *fakeSubjects) ClaimSubject(_ context.Context, placeholder, s identity.Subject) (identity.Identity, error) {
id, ok := f.bindings[placeholder]
if !ok {
return identity.Identity{}, identity.ErrNotFound
}
delete(f.bindings, placeholder)
f.bindings[s] = id
return f.byID[id], nil
}
func (f *fakeSubjects) BindSubject(_ context.Context, id identity.IdentityID, s identity.Subject, _ identity.Audit) error {
f.bindings[s] = id
return nil
}
// TestOrgMemberAdd holds adding a person by provider subject or email: it
// needs the admin grant, owner needs an owner, one identifier is required, and
// the person who was added signs in as the identity the membership names, by
// subject or by the provider's verified email.
func TestOrgMemberAdd(t *testing.T) {
const issuer = "https://idp.example"
engine := infraaccess.New(access.ShippedOrgPolicies(org.DefaultOrgID))
members := "/api/orgs/" + string(org.DefaultOrgID) + "/members"
tests := []struct {
name string
caller string
body string
wantStatus int
signIn identity.Credential
wantRole org.Role
// later is a second account showing the same verified email after
// the first sign-in claimed it; it must not sign in.
later identity.Credential
}{
{
"an admin adds by subject", "admin", `{"subject":"sub-1","role":"developer"}`, http.StatusCreated,
identity.Credential{Subject: identity.Subject{Issuer: issuer, Subject: "sub-1"}},
org.RoleDeveloper,
identity.Credential{},
},
{
"an admin adds by email and the verified email signs in", "admin", `{"email":"Ann@Example.com","role":"viewer"}`, http.StatusCreated,
identity.Credential{Subject: identity.Subject{Issuer: issuer, Subject: "unseen"}, Email: "ann@example.com"},
org.RoleViewer,
identity.Credential{Subject: identity.Subject{Issuer: issuer, Subject: "impostor"}, Email: "ann@example.com"},
},
{
"an unverified email does not sign in", "admin", `{"email":"ann@example.com","role":"viewer"}`, http.StatusCreated,
identity.Credential{Subject: identity.Subject{Issuer: issuer, Subject: "unseen"}},
"",
identity.Credential{},
},
{"an admin cannot add an owner", "admin", `{"subject":"sub-1","role":"owner"}`, http.StatusForbidden, identity.Credential{}, "", identity.Credential{}},
{
"an owner adds an owner", "owner", `{"subject":"sub-1","role":"owner"}`, http.StatusCreated,
identity.Credential{Subject: identity.Subject{Issuer: issuer, Subject: "sub-1"}},
org.RoleOwner,
identity.Credential{},
},
{"a developer cannot add", "developer", `{"subject":"sub-1","role":"viewer"}`, http.StatusForbidden, identity.Credential{}, "", identity.Credential{}},
{"both identifiers are refused", "admin", `{"subject":"a","email":"a@b.c","role":"viewer"}`, http.StatusBadRequest, identity.Credential{}, "", identity.Credential{}},
{"neither identifier is refused", "admin", `{"role":"viewer"}`, http.StatusBadRequest, identity.Credential{}, "", identity.Credential{}},
{"an unknown role is refused", "admin", `{"subject":"sub-1","role":"superuser"}`, http.StatusBadRequest, identity.Credential{}, "", identity.Credential{}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
orgs := newFakeOrgs()
store := &fakeSubjects{byID: map[identity.IdentityID]identity.Identity{}, bindings: map[identity.Subject]identity.IdentityID{}}
s := &Server{
Access: engine, Principals: rolePrincipals{}, Orgs: orgs,
Identities: store, Subjects: store, Issuer: issuer,
Authenticate: func(_ context.Context, token string) (identity.Identity, error) {
return identity.Identity{ID: identity.IdentityID(token), Kind: identity.KindUser}, nil
},
}
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, members, strings.NewReader(tt.body))
req.Header.Set("Authorization", "Bearer "+tt.caller)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
orgRoutes(s).ServeHTTP(rec, req)
if rec.Code != tt.wantStatus {
t.Fatalf("status = %d, want %d, body %s", rec.Code, tt.wantStatus, rec.Body.String())
}
if tt.wantStatus != http.StatusCreated {
if len(store.byID) != 0 {
t.Fatalf("a refused request created %d identities", len(store.byID))
}
return
}
got, err := identity.Resolve(t.Context(), store, tt.signIn)
if tt.wantRole == "" {
if !errors.Is(err, identity.ErrSubjectUnbound) {
t.Fatalf("Resolve = %v, want ErrSubjectUnbound", err)
}
return
}
if err != nil {
t.Fatalf("Resolve: %v", err)
}
var role org.Role
for _, m := range orgs.members[org.DefaultOrgID] {
if m.IdentityID == got.ID {
role = m.Role
}
}
if role != tt.wantRole {
t.Fatalf("signed-in role = %q, want %q", role, tt.wantRole)
}
if tt.later.Subject.Subject == "" {
return
}
if _, err := identity.Resolve(t.Context(), store, tt.later); !errors.Is(err, identity.ErrSubjectUnbound) {
t.Fatalf("second account with the same email: Resolve = %v, want ErrSubjectUnbound", err)
}
again, err := identity.Resolve(t.Context(), store, identity.Credential{Subject: tt.signIn.Subject})
if err != nil || again.ID != got.ID {
t.Fatalf("first account by subject alone = %v, %v, want %s", again.ID, err, got.ID)
}
})
}
}
// 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
// wantWorkspace is a workspace the acting principal must carry,
// the selected org's own and not another's.
wantWorkspace org.WorkspaceID
}{
{"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"`, "acme-ws"},
{"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"})
orgs.workspaces["acme"] = []org.Workspace{{ID: "acme-ws", OrgID: "acme"}}
chain := &recordingChain{}
s := &Server{
Access: chain, 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 != "" {
sendCookie(req, s.cookies().org, 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)
}
if tt.wantWorkspace != "" && !slices.ContainsFunc(chain.last.Workspaces, func(w org.Workspace) bool { return w.ID == tt.wantWorkspace }) {
t.Fatalf("acting principal workspaces = %v, want %q", chain.last.Workspaces, tt.wantWorkspace)
}
})
}
}
// recordingChain allows everything and keeps the last principal it judged.
type recordingChain struct{ last access.Principal }
func (c *recordingChain) Authorize(_ context.Context, p access.Principal, _ access.Action, _ access.Resource, _ access.Context) access.Decision {
c.last = p
return access.Allowed()
}
func (*recordingChain) Ready() bool { return true }