Files

419 lines
18 KiB
Go

package webui
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
infraaccess "github.com/samcharles93/archie-core/internal/infrastructure/access"
)
// operator is the person owner the upgrade creates and the shared-token
// session acts as.
func operator() access.Principal {
return access.Principal{
IdentityID: identity.OperatorID(),
Org: org.DefaultOrgID,
Memberships: []org.Membership{
{IdentityID: identity.OperatorID(), OrgID: org.DefaultOrgID, Role: org.RoleOwner},
},
}
}
// stubPrincipals answers the operator's own principal and a bare one for
// anyone else.
func stubPrincipals(haveOperator bool) access.PrincipalSource {
return operatorPrincipals{haveOperator: haveOperator}
}
type operatorPrincipals struct{ haveOperator bool }
func (s operatorPrincipals) PrincipalFor(_ context.Context, id identity.IdentityID) (access.Principal, error) {
if s.haveOperator && id == identity.OperatorID() {
return operator(), nil
}
return access.Principal{IdentityID: id, Org: org.DefaultOrgID}, nil
}
type allowAll struct{}
func (allowAll) Authorize(context.Context, access.Principal, access.Action, access.Resource, access.Context) access.Decision {
return access.Allowed()
}
func (allowAll) Ready() bool { return true }
// notReadyChain is an authorizer whose engine has not loaded: every decision
// is the not-loaded refusal, which no policy evaluated.
type notReadyChain struct{}
func (notReadyChain) Authorize(context.Context, access.Principal, access.Action, access.Resource, access.Context) access.Decision {
return access.Unavailable()
}
func (notReadyChain) Ready() bool { return false }
type recordingTokens struct{ owner identity.IdentityID }
// AddPersonalToken mirrors the State Store's rule: only a signed-in person's
// principal may own a personal token.
func (t *recordingTokens) AddPersonalToken(ctx context.Context, _ identity.Subject, _ string, _ *time.Time) error {
p, ok := access.PrincipalFromContext(ctx)
if !ok || p.IdentityID == identity.SystemID || p.Role("") != org.RoleOwner {
return identity.ErrInvalid
}
t.owner = p.IdentityID
return nil
}
func (*recordingTokens) ListPersonalTokens(context.Context) ([]identity.PersonalToken, error) {
return nil, nil
}
func (*recordingTokens) RevokePersonalToken(context.Context, string) error { return nil }
// TestSharedTokenPrincipal pins who the dashboard acts as when no provider
// signed anyone in: the org-sys owner person when the upgrade made one, the
// system owner otherwise.
func TestSharedTokenPrincipal(t *testing.T) {
tests := []struct {
name string
principals access.PrincipalSource
want identity.IdentityID
}{
{"the operator person owns the shared session", stubPrincipals(true), identity.OperatorID()},
{"with no operator the system owner remains", stubPrincipals(false), identity.SystemID},
{"with no principal source the system owner remains", nil, identity.SystemID},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &Server{Principals: tt.principals}
p, err := s.requestPrincipal(t.Context())
if err != nil {
t.Fatal(err)
}
if p.IdentityID != tt.want {
t.Fatalf("principal = %q, want %q", p.IdentityID, tt.want)
}
})
}
}
// TestSharedTokenOperatorPostsPersonalToken drives the whole dashboard path:
// the shared token resolves to the operator, the token route accepts it where
// the system principal was refused, and a write's audit names the operator.
func TestSharedTokenOperatorPostsPersonalToken(t *testing.T) {
tokens := &recordingTokens{}
s := &Server{
Token: "shared",
Access: allowAll{},
Principals: stubPrincipals(true),
PersonalTokens: tokens,
}
handler := s.requireToken(s.authorize(http.HandlerFunc(newIdentitiesAPI(s).handlePersonalTokenCreate)))
rec := httptest.NewRecorder()
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/tokens", strings.NewReader(`{"name":"ci","days":30}`))
req.Header.Set("Authorization", "Bearer shared")
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusCreated {
t.Fatalf("POST /api/tokens = %d, body %s", rec.Code, rec.Body.String())
}
if tokens.owner != identity.OperatorID() {
t.Fatalf("token owner = %q, want the operator", tokens.owner)
}
audit, err := webAudit(access.WithPrincipal(t.Context(), operator()))
if err != nil {
t.Fatal(err)
}
if audit.ActorID != identity.OperatorID() {
t.Fatalf("audit actor = %q, want the operator", audit.ActorID)
}
}
// TestAuthorizeRefusesWithoutAChain pins the gate for a server with no chain
// and for a chain that has not loaded: the request is refused rather than
// served as the system org, and nothing is written.
func TestAuthorizeRefusesWithoutAChain(t *testing.T) {
tests := []struct {
name string
srv *Server
method, path, accept string
body string
}{
{name: "no chain", srv: &Server{}, method: http.MethodPost, path: "/api/tokens"},
{name: "chain not loaded", srv: &Server{Access: notReadyChain{}}, method: http.MethodPost, path: "/api/tokens"},
// An outage is not a credential failure, so the browser notice is 503
// too.
{name: "chain not loaded, browser", srv: &Server{Access: notReadyChain{}}, method: http.MethodGet, path: "/tasks", accept: "text/html"},
// The health report still says why, naming only the chain.
{name: "chain not loaded, health detail", srv: &Server{Access: notReadyChain{}}, method: http.MethodGet, path: healthDetailedRoute, body: `"name":"access_policies"`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tokens := &recordingTokens{}
tt.srv.Token = "shared"
tt.srv.Principals = stubPrincipals(true)
tt.srv.PersonalTokens = tokens
handler := tt.srv.requireToken(tt.srv.authorize(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
t.Fatal("the handler must not be reached")
})))
rec := httptest.NewRecorder()
req := httptest.NewRequestWithContext(t.Context(), tt.method, tt.path, nil)
req.Header.Set("Authorization", "Bearer shared")
if tt.accept != "" {
req.Header.Set("Accept", tt.accept)
}
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503", rec.Code)
}
if !strings.Contains(rec.Body.String(), tt.body) {
t.Fatalf("body = %q, want it to contain %q", rec.Body.String(), tt.body)
}
if tokens.owner != "" {
t.Fatalf("token owner = %q, want no write", tokens.owner)
}
})
}
}
func TestAdministrationRoutes(t *testing.T) {
tests := []struct {
method, path string
action access.Action
}{
{http.MethodGet, "/api/extensions", access.ActionRead},
{http.MethodPost, "/api/extensions", access.ActionManageIdentities},
{http.MethodPost, "/api/extensions/bws/accept", access.ActionManageIdentities},
{http.MethodPut, "/api/extensions/bws/enabled", access.ActionManageIdentities},
{http.MethodDelete, "/api/extensions/bws", access.ActionDelete},
{http.MethodGet, "/api/access/policies", access.ActionRead},
{http.MethodPut, "/api/access/policies", access.ActionManagePolicies},
{http.MethodDelete, "/api/access/policies", access.ActionManagePolicies},
{http.MethodGet, "/api/schedules", access.ActionRead},
{http.MethodPut, "/api/schedules/nightly", access.ActionManageIdentities},
{http.MethodPost, "/api/schedules/nightly/runs", access.ActionManageIdentities},
{http.MethodDelete, "/api/schedules/nightly", access.ActionDelete},
}
for _, tt := range tests {
t.Run(tt.method+" "+tt.path, func(t *testing.T) {
action, kind, _ := accessRequest(httptest.NewRequestWithContext(t.Context(), tt.method, tt.path, nil))
if action != tt.action || kind != access.KindPolicy {
t.Fatalf("accessRequest = %q on %q, want %q on %q", action, kind, tt.action, access.KindPolicy)
}
})
}
}
func TestChannelReloadRoute(t *testing.T) {
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/channels/telegram/reload", nil)
action, kind, key := accessRequest(req)
if action != access.ActionManageIdentities || kind != access.KindDashboard || key != "telegram" {
t.Fatalf("accessRequest = %q on %q (%q), want %q on %q (telegram)", action, kind, key, access.ActionManageIdentities, access.KindDashboard)
}
}
// TestChatRouteMapping pins the chat routes' actions: posting a message runs a
// workflow, while triggering or deferring an update changes the update object
// on the dashboard kind, so a scoped grant can carry it without any run right.
func TestChatRouteMapping(t *testing.T) {
tests := []struct {
method, path string
action access.Action
kind access.ResourceKind
id string
}{
{http.MethodPost, "/api/chat/update/install", access.ActionUpdate, access.KindDashboard, "update"},
{http.MethodPost, "/api/chat/update/defer", access.ActionUpdate, access.KindDashboard, "update"},
{http.MethodPost, "/api/chat/stream", access.ActionRun, access.KindWorkflow, ""},
{http.MethodPost, "/api/chat/cancel", access.ActionRun, access.KindWorkflow, ""},
{http.MethodPost, "/api/chat/answer", access.ActionRun, access.KindWorkflow, ""},
{http.MethodGet, "/api/chat/update", access.ActionRead, access.KindDashboard, ""},
{http.MethodGet, "/api/chat/sessions", access.ActionRead, access.KindDashboard, ""},
}
for _, tt := range tests {
t.Run(tt.method+" "+tt.path, func(t *testing.T) {
action, kind, id := accessRequest(httptest.NewRequestWithContext(t.Context(), tt.method, tt.path, nil))
if action != tt.action || kind != tt.kind || id != tt.id {
t.Fatalf("accessRequest = %q on %q (%q), want %q on %q (%q)", action, kind, id, tt.action, tt.kind, tt.id)
}
})
}
}
func TestPersonalTokensWithoutPerson(t *testing.T) {
for _, method := range []string{http.MethodGet, http.MethodPost, http.MethodDelete} {
t.Run(method, func(t *testing.T) {
s := &Server{PersonalTokens: &recordingTokens{}}
req := httptest.NewRequestWithContext(access.WithPrincipal(t.Context(), access.SharedTokenOwner()), method, "/api/tokens", nil)
rec := httptest.NewRecorder()
switch method {
case http.MethodGet:
newIdentitiesAPI(s).handlePersonalTokensList(rec, req)
case http.MethodPost:
newIdentitiesAPI(s).handlePersonalTokenCreate(rec, req)
case http.MethodDelete:
newIdentitiesAPI(s).handlePersonalTokenRevoke(rec, req)
}
if method == http.MethodGet {
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"available":false`) {
t.Fatalf("list without person = %d %s", rec.Code, rec.Body.String())
}
} else if rec.Code != http.StatusForbidden || strings.TrimSpace(rec.Body.String()) != "Personal tokens need a signed-in person." {
t.Fatalf("mutation without person = %d %s", rec.Code, rec.Body.String())
}
})
}
}
// sourcesIn serves GetSource, the one read authorization makes: one source
// per path, in the workspace it names.
type sourcesIn struct {
storecontract.SourceStore
workspaces map[string]org.WorkspaceID
}
func (s sourcesIn) GetSource(_ context.Context, path string) (*source.Source, error) {
ws, ok := s.workspaces[path]
if !ok {
return nil, nil
}
return &source.Source{Path: path, OrgID: org.DefaultOrgID, WorkspaceID: ws}, nil
}
type principalOf access.Principal
func (p principalOf) PrincipalFor(context.Context, identity.IdentityID) (access.Principal, error) {
return access.Principal(p), nil
}
// TestAuthorizeRecord pins that a request for a record is decided in that
// record's scope: its workspace's policies and the role held there, and the
// record's own object policies.
func TestAuthorizeRecord(t *testing.T) {
member := func(id identity.IdentityID, role org.Role, workspaces ...org.Membership) access.Principal {
return access.Principal{IdentityID: id, Org: org.DefaultOrgID, Memberships: append([]org.Membership{
{IdentityID: id, OrgID: org.DefaultOrgID, Role: role},
}, workspaces...)}
}
dev := member("dev", org.RoleDeveloper, org.Membership{IdentityID: "dev", OrgID: org.DefaultOrgID, WorkspaceID: "locked", Role: org.RoleViewer})
ops, admin := member("ops", org.RoleAdmin), member("admin", org.RoleAdmin)
policies := append(access.ShippedOrgPolicies(org.DefaultOrgID),
access.Policy{
ID: "prod-open", Level: access.LevelWorkspace, OrgID: org.DefaultOrgID, WorkspaceID: "prod",
Text: `permit(principal, action, resource);`,
},
access.Policy{
ID: "prod-frozen", Level: access.LevelWorkspace, OrgID: org.DefaultOrgID, WorkspaceID: "prod",
Text: `forbid(principal, action == Archie::Action::"update", resource);`,
},
access.Policy{
ID: "ops-reads-it", Level: access.LevelObject, OrgID: org.DefaultOrgID, ObjectKind: access.KindSecret, ObjectID: "in-default",
Text: `permit(principal, action, resource) when { principal == Archie::Identity::"ops" };`,
},
)
sources := sourcesIn{workspaces: map[string]org.WorkspaceID{
"in-default": org.DefaultWorkspaceID, "in-prod": "prod", "in-locked": "locked",
}}
tests := []struct {
name, method, path string
principal access.Principal
want int
}{
{"the org role edits a default-workspace record", http.MethodPut, "/api/sources/in-default/name", dev, http.StatusOK},
{"a workspace forbid denies the edit there", http.MethodPut, "/api/sources/in-prod/name", dev, http.StatusForbidden},
{"the forbid leaves reads alone", http.MethodGet, "/api/sources/in-prod", dev, http.StatusOK},
{"a workspace viewer role replaces the org developer role", http.MethodPut, "/api/sources/in-locked/name", dev, http.StatusForbidden},
{"the workspace role still reads", http.MethodGet, "/api/sources/in-locked", dev, http.StatusOK},
{"a developer does not read a secret", http.MethodPost, "/api/sources/in-prod/secret", dev, http.StatusForbidden},
{"an admin reads a secret", http.MethodPost, "/api/sources/in-prod/secret", admin, http.StatusOK},
{"an object policy narrows who reads it", http.MethodPost, "/api/sources/in-default/secret", admin, http.StatusForbidden},
{"the reader it names still does", http.MethodPost, "/api/sources/in-default/secret", ops, http.StatusOK},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &Server{Access: infraaccess.New(policies), Principals: principalOf(tt.principal), Sources: sources}
handler := s.authorize(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
req := httptest.NewRequestWithContext(WithActingIdentity(t.Context(), identity.Identity{ID: tt.principal.IdentityID}), tt.method, tt.path, nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != tt.want {
t.Fatalf("%s %s = %d, want %d", tt.method, tt.path, rec.Code, tt.want)
}
})
}
}
// TestAuthorizeCreateIn pins that a create is decided in the workspace its
// body names, where the role held there replaces the org role.
func TestAuthorizeCreateIn(t *testing.T) {
dev := access.Principal{IdentityID: "dev", Org: org.DefaultOrgID, Memberships: []org.Membership{
{IdentityID: "dev", OrgID: org.DefaultOrgID, Role: org.RoleDeveloper},
{IdentityID: "dev", OrgID: org.DefaultOrgID, WorkspaceID: "locked", Role: org.RoleViewer},
}}
tests := []struct {
name string
workspace org.WorkspaceID
want int
}{
{"the default workspace was decided at the route", "", http.StatusOK},
{"a workspace the org role covers", "open", http.StatusOK},
{"a workspace where the caller is only a viewer", "locked", http.StatusForbidden},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := &Server{Access: infraaccess.New(access.ShippedOrgPolicies(org.DefaultOrgID))}
req := httptest.NewRequestWithContext(access.WithPrincipal(t.Context(), dev), http.MethodPost, "/api/sources", nil)
rec := httptest.NewRecorder()
if s.authorizeCreateIn(rec, req, access.KindSource, tt.workspace) {
rec.WriteHeader(http.StatusOK)
}
if rec.Code != tt.want {
t.Fatalf("create in %q = %d, want %d", tt.workspace, rec.Code, tt.want)
}
})
}
}
type taskAttributesStore struct {
storecontract.TaskStore
owner, status string
}
func (s taskAttributesStore) TaskByID(context.Context, int64) (*task.Task, error) {
return &task.Task{ID: 7, Identity: s.owner, Status: s.status, Workspace: "default"}, nil
}
func TestTaskAuthorizationUsesStoredAttributes(t *testing.T) {
policy := access.Policy{ID: "owned-queued", Level: access.LevelObject, OrgID: "acme", ObjectKind: access.KindTask, ObjectID: "7", Text: `permit(principal,action,resource) when {resource.owner == "alice" && resource.state == "queued"};`}
p := access.Principal{IdentityID: "alice", Org: "acme", Memberships: []org.Membership{{IdentityID: "alice", OrgID: "acme", Role: org.RoleDeveloper}}}
for _, tc := range []struct {
name, owner, state string
want int
}{
{"owned queued task", "alice", "queued", 200},
{"other owner", "bob", "queued", 403},
{"different state", "alice", "running", 403},
} {
t.Run(tc.name, func(t *testing.T) {
srv := &Server{Store: taskAttributesStore{owner: tc.owner, status: tc.state}, Access: infraaccess.New(append(access.ShippedOrgPolicies("acme"), policy)), Principals: principalOf(p)}
req := httptest.NewRequestWithContext(WithActingIdentity(t.Context(), identity.Identity{ID: "alice"}), "PUT", "https://archie.example/api/tasks/7", strings.NewReader(`{"owner":"alice","state":"queued"}`))
rec := httptest.NewRecorder()
srv.authorize(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})).ServeHTTP(rec, req)
if rec.Code != tc.want {
t.Fatalf("status=%d want=%d body=%s", rec.Code, tc.want, rec.Body.String())
}
})
}
}