* fix(postgres): scope OpenPRs to the caller's org A principal-carrying caller read every org's pr_open tasks. The query now honours the request scope; the daemon's unscoped review scan still sees all orgs. Issue: archie-core-kgxw.23 * fix(statestore): serve task logs only to the task's org ReadTaskLog and StreamTaskLogContent took a task ID and read the file with no org check. The State Store's task-log reader now confirms the task is visible under the caller's scope first; unscoped services read as before. Issue: archie-core-kgxw.24 * fix(postgres): scope ListPolicies to the caller's org Every org's policy text reached any principal-carrying caller. A scoped read now sees its own org's policies, plus instance policies when scoped to the system org. The engines and the lockout guard decide for every org, so they read the full chain unscoped: the dashboard engine loads without the request's principal and the guard lifts the caller's scope. Issue: archie-core-kgxw.25 * fix(postgres): scope identity reads to the caller's org ListIdentities and GetIdentity (and its alias fallback) returned every identity to any caller. A caller scoped to an org now sees only that org's members and assigned agents; the system org and unscoped services still see the whole instance. Issue: archie-core-kgxw.26 * fix(postgres): hide instance status from other orgs ListPresence, ListChannelStatus, ListApplyStatus and GetConfigSnapshot answered any org principal with instance-wide state. They now return nothing unless the request is unscoped or scoped to the system org. The dashboard reads the published config as itself, since its handlers project it for callers of every org. Issue: archie-core-kgxw.27 * feat(postgres): assign new agents an org and role at creation A bot or service account created through the API served no org until the next State Store boot granted it one. Create now assigns it to the org the request acts in with the developer role in the same transaction, so it is authorized immediately. Issue: archie-core-kgxw.14 * feat(edastore): create event records in a chosen workspace Sources are created in a workspace of the caller's org, the default one when none is named; event types and bindings take their source's workspace and mappings their event type's, the same rule the org backfill applied. The binding, mapping and event type contracts carry the workspace, the four list endpoints accept ?workspace=, and the Events page has a workspace selector that filters every step and picks where a new source goes. Issue: archie-core-kgxw.11 * feat(webui): authorize a record in its workspace The API built every access request with no workspace, so workspace policies and per-workspace roles never applied. A request naming a source, binding, mapping, event type or task now reads the record's workspace under the caller's scope and authorizes in it; tasks carry their workspace on the State Store contract for this. Issue: archie-core-kgxw.9 * feat(access): expose workspace environment to policies Policies can test resource.workspace.environment. The workspace attribute is the workspace entity, which carries its environment; the principal brings its org's workspaces from the State Store, so the dashboard and the daemon's run checks describe a resource's workspace without another lookup, and the daemon now authorizes runs in the task's or binding's workspace. Issue: archie-core-kgxw.10 * fix(webui): ask read_secret when a source secret is read Rotating a source's secret returns its value, but the route asked update, which every developer holds, so no policy could narrow who reads a secret. It now asks read_secret on the secret, which the shipped roles give admins and an object policy can narrow further. Issue: archie-core-kgxw.17 * refactor(org): delete the unused upgrade-incomplete sentinel Nothing returns org.ErrUpgradeIncomplete: the State Store finishes the org upgrade before it serves. Issue: archie-core-kgxw.18
314 lines
12 KiB
Go
314 lines
12 KiB
Go
package webui
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"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"
|
|
"github.com/samcharles93/archie-core/internal/domain/source"
|
|
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
|
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(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(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) 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(s.handlePersonalTokenCreate)))
|
|
rec := httptest.NewRecorder()
|
|
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/tokens", nil)
|
|
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},
|
|
}
|
|
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 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:
|
|
s.handlePersonalTokensList(rec, req)
|
|
case http.MethodPost:
|
|
s.handlePersonalTokenCreate(rec, req)
|
|
case http.MethodDelete:
|
|
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)
|
|
}
|
|
})
|
|
}
|
|
}
|