Files

509 lines
19 KiB
Go

package webui
import (
"context"
"encoding/json"
"errors"
"net"
"net/http"
"strconv"
"strings"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// authorize wraps h with the policy chain. A chain that is absent or has not
// loaded refuses the request: the credential check alone is never the gate
// while orgs exist, so a State Store outage closes the dashboard rather than
// letting every request through as the system org.
func (s *Server) authorize(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Checked before the principal: resolving it is a State Store round
// trip, which buys nothing when the answer is a refusal anyway.
if s.Access == nil || !s.Access.Ready() {
s.refuseUngated(w, r)
return
}
principal, err := s.requestPrincipal(r.Context())
if err != nil {
if wantsDocument(r) {
s.authPage(w, http.StatusUnauthorized, "Sign-in could not resolve your org.")
return
}
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
}
ctx := org.WithOrg(access.WithPrincipal(r.Context(), principal), principal.Org)
action, kind, id := accessRequest(r.WithContext(ctx))
// The record's org is not loaded here: org-filtered lookups keep a
// record of another org from ever being fetched, and this request's
// record (when it has an ID) belongs to the caller's org. The
// workspace, owner and state are read from the record, never the body.
resource, err := s.recordResource(ctx, kind, id)
if err != nil {
s.logf("record workspace unavailable", "kind", kind, "id", id, "err", err)
http.Error(w, "record unavailable", http.StatusServiceUnavailable)
return
}
peer, _, _ := net.SplitHostPort(r.RemoteAddr)
decision := s.Access.Authorize(ctx, principal, action, resource, access.Context{Addr: peer})
if !decision.Allowed {
if errors.Is(decision.Err, access.ErrChainUnavailable) {
// Nothing was evaluated: the chain has not loaded. This is an
// availability failure, not a denial, so none is recorded.
s.refuseUngated(w, r)
return
}
s.recordDenial(r.Context(), principal, action, resource, decision)
if wantsDocument(r) {
s.authPage(w, http.StatusUnauthorized, "You do not have permission to do that.")
return
}
// A denial inside the caller's org is forbidden, without the
// reason.
http.Error(w, "forbidden", http.StatusForbidden)
return
}
// The principal rides the context into every State Store call, which
// derives the org it acts in from it.
h.ServeHTTP(w, r.WithContext(ctx))
})
}
// authorizeCreateIn checks a create against the workspace the body names, which
// the route-level check cannot see: no record exists yet to read it from. An
// empty workspace is the default one, which that check already covered.
func (s *Server) authorizeCreateIn(w http.ResponseWriter, r *http.Request, kind access.ResourceKind, workspace org.WorkspaceID) bool {
principal, ok := access.PrincipalFromContext(r.Context())
if workspace == "" || !ok {
return true
}
resource := access.Resource{Kind: kind, Org: principal.Org, Workspace: workspace}
decision := s.Access.Authorize(r.Context(), principal, access.ActionCreate, resource, access.Context{})
if decision.Allowed {
return true
}
s.recordDenial(r.Context(), principal, access.ActionCreate, resource, decision)
http.Error(w, "forbidden", http.StatusForbidden)
return false
}
// recordResource reads policy attributes from the stored record, never the body.
func (s *Server) recordResource(ctx context.Context, kind access.ResourceKind, id string) (access.Resource, error) {
resource := access.Resource{Kind: kind, ID: id, Org: org.OrgFromContext(ctx)}
if id == "" {
return resource, nil
}
var err error
switch kind {
case access.KindTask:
return s.taskResource(ctx, resource)
case access.KindBinding:
return s.bindingResource(ctx, resource)
case access.KindSource:
resource.Workspace, err = s.sourceWorkspace(ctx, id)
case access.KindMapping:
resource.Workspace, err = s.mappingWorkspace(ctx, id)
case access.KindEventType:
resource.Workspace, err = s.eventTypeWorkspace(ctx, id)
}
return resource, err
}
func (s *Server) sourceWorkspace(ctx context.Context, path string) (org.WorkspaceID, error) {
if s.Sources == nil {
return "", nil
}
src, err := s.Sources.GetSource(ctx, path)
if src == nil || err != nil {
return "", err
}
return src.WorkspaceID, nil
}
func (s *Server) bindingResource(ctx context.Context, resource access.Resource) (access.Resource, error) {
if s.Bindings == nil {
return resource, nil
}
b, err := s.Bindings.GetBinding(ctx, resource.ID)
if b == nil || err != nil {
return resource, ignoreNotFound(err, storecontract.ErrBindingNotFound)
}
resource.Workspace, resource.State = b.WorkspaceID, string(b.Status)
return resource, nil
}
func (s *Server) mappingWorkspace(ctx context.Context, id string) (org.WorkspaceID, error) {
if s.Mappings == nil {
return "", nil
}
m, err := s.Mappings.GetMapping(ctx, id)
if m == nil || err != nil {
return "", ignoreNotFound(err, storecontract.ErrMappingNotFound)
}
return m.WorkspaceID, nil
}
func (s *Server) eventTypeWorkspace(ctx context.Context, id string) (org.WorkspaceID, error) {
if s.EventTypes == nil {
return "", nil
}
types, err := s.EventTypes.ListEventTypes(ctx)
if err != nil {
return "", err
}
for _, t := range types {
if t.ID == id {
return t.WorkspaceID, nil
}
}
return "", nil
}
func (s *Server) taskResource(ctx context.Context, resource access.Resource) (access.Resource, error) {
taskID, ok := numericID(resource.ID)
if !ok {
return resource, nil
}
t, err := s.Store.TaskByID(ctx, taskID)
if t == nil || err != nil {
return resource, err
}
resource.Workspace, resource.Owner, resource.State = t.Workspace, identity.IdentityID(t.Identity), t.Status
return resource, nil
}
// numericID parses a task route's ID; any other segment names no task.
func numericID(id string) (int64, bool) {
n, err := strconv.ParseInt(id, 10, 64)
return n, err == nil
}
// ignoreNotFound drops the store's not-found answer: a missing record has no
// workspace, and the handler reports it.
func ignoreNotFound(err, notFound error) error {
if errors.Is(err, notFound) {
return nil
}
return err
}
// refuseUngated answers a request the dashboard cannot authorize because no
// policy chain is available. It serves nothing ungated: without a chain the
// credential check would be the whole gate and every call would act as the
// system org. The detailed health report names only the unloaded chain, so
// the operator can see why without any other probe being served ungated.
func (s *Server) refuseUngated(w http.ResponseWriter, r *http.Request) {
if wantsDocument(r) {
s.authPage(w, http.StatusServiceUnavailable, "The access policy chain is not available yet.")
return
}
w.Header().Set("Cache-Control", "no-store")
if r.URL.Path == healthDetailedRoute {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusServiceUnavailable)
_ = json.NewEncoder(w).Encode(health.Report{Status: health.StatusDegraded, Components: []health.Component{{
Name: "access_policies", Status: health.StatusDegraded, Detail: "policies not loaded; requests refused",
}}})
return
}
http.Error(w, "access policies are not available", http.StatusServiceUnavailable)
}
// requestPrincipal assembles the principal a request acts as. With no acting
// identity (the shared token), it is the org-sys owner person when the upgrade
// created one; with an acting identity, it is the identity's org and
// memberships, read over the wire. The system owner remains the fallback for an
// install that has not run the operator phase.
func (s *Server) requestPrincipal(ctx context.Context) (access.Principal, error) {
if acting, ok := ActingIdentity(ctx); ok {
if s.Principals == nil {
return access.Principal{}, errPrincipalsUnavailable
}
return s.Principals.PrincipalFor(ctx, acting.ID)
}
if s.Principals != nil {
if operator, err := s.Principals.PrincipalFor(ctx, identity.OperatorID()); err == nil &&
operator.Org == org.DefaultOrgID && operator.Role("") == org.RoleOwner {
return operator, nil
}
}
return access.SharedTokenOwner(), nil
}
func (s *Server) recordDenial(ctx context.Context, p access.Principal, action access.Action, r access.Resource, decision access.Decision) {
if s.Denials == nil {
return
}
denial := access.Denial{
Principal: p.IdentityID, Org: p.Org, Action: action,
Kind: r.Kind, ResourceID: r.ID, Level: decision.Level,
Policies: decision.Policies,
}
if err := s.Denials.RecordDenial(ctx, denial); err != nil && s.Log != nil {
s.Log.ErrorContext(ctx, "record access denial", "err", err)
}
}
// errPrincipalsUnavailable is the answer of a dashboard wired with the chain
// but without the principal assembly, which is a composition error: the two
// are wired together or not at all.
var errPrincipalsUnavailable = &notWiredError{}
type notWiredError struct{}
func (*notWiredError) Error() string { return "webui: principal assembly not wired" }
// accessRequest derives the action, resource kind and record key of one API
// request from its method and path. Unmapped routes read the dashboard
// itself, so a new route is never wider than read until it is mapped.
func accessRequest(r *http.Request) (access.Action, access.ResourceKind, string) {
action := actionOf(r.Method)
path := r.URL.Path
if matchPrefix(path, "/api/audit") {
// The feed spans every trail, so reading it is its own action: the
// export route below the same prefix carries the same grant.
return access.ActionReadAudit, access.KindAudit, ""
}
if matchPrefix(path, "/api/usage") {
// Who spent what is its own grant, not a viewer's broad read.
return access.ActionReadUsage, access.KindDashboard, ""
}
if a, kind, id, ok := routeOverride(r, action, path); ok {
return a, kind, id
}
return action, kindOf(path), segmentValue(path, 2)
}
// actionOf maps the HTTP method onto the action vocabulary. POST is create:
// the route refinements lift the routes whose write is something else.
func actionOf(method string) access.Action {
switch method {
case http.MethodPost:
return access.ActionCreate
case http.MethodPut, http.MethodPatch:
return access.ActionUpdate
case http.MethodDelete:
return access.ActionDelete
}
return access.ActionRead
}
// routeOverride returns the action, kind and record key a specific route
// shape carries, or ok=false when the method-and-kind fallback applies.
func routeOverride(r *http.Request, action access.Action, path string) (access.Action, access.ResourceKind, string, bool) {
if a, kind, ok := accountRoute(path); ok {
return a, kind, "", true
}
if command, ok := bindingCommand(action, path); ok {
return command, access.KindBinding, segmentValue(path, 2), true
}
switch {
case matchSegment(path, "/api/tasks/", "/logs"):
return access.ActionReadLogs, access.KindTask, segmentValue(path, 2), true
case matchPrefix(path, "/api/access"):
return accessRoute(action, path)
case matchPrefix(path, "/api/identities"):
return actionManage(action), access.KindIdentity, segmentValue(path, 2), true
case matchPrefix(path, "/api/orgs"):
return orgRouteAction(action, path), access.KindOrg, segmentValue(path, 2), true
case matchPrefix(path, "/api/schedules"):
return scheduleRoute(r, action, path)
case matchPrefix(path, "/api/extensions"):
// Installing and enabling an extension runs a process on the host.
return actionManage(action), access.KindPolicy, segmentValue(path, 2), true
case matchPrefix(path, "/api/control-plane/resources"):
return controlPlaneResourceRoute(action, path)
case updateCommandRoute(action, path):
// Triggering or deferring an install changes the update object, not
// a workflow run: the dashboard kind carries the update's policy.
return access.ActionUpdate, access.KindDashboard, "update", true
case matchPrefix(path, "/api/chat"):
return chatRoute(action)
case matchSegment(path, "/api/sources/", "/secret"):
// Rotating a source's secret hands back its value.
return access.ActionReadSecret, access.KindSecret, segmentValue(path, 2), true
case matchPrefix(path, "/api/channels"), matchPrefix(path, "/api/config"),
matchPrefix(path, "/api/logs"), matchPrefix(path, "/api/tokens"):
return dashboardRoute(action, path)
}
return action, "", "", false
}
// dashboardRoute maps the dashboard's own routes: channel settings are
// instance administration, while config, logs and a person's own tokens act
// only as that person, needing no more than a dashboard read.
func dashboardRoute(action access.Action, path string) (access.Action, access.ResourceKind, string, bool) {
if matchPrefix(path, "/api/channels") {
return actionManage(action), access.KindDashboard, segmentValue(path, 2), true
}
return access.ActionRead, access.KindDashboard, "", true
}
// scheduleRoute maps a schedule request. A schedule the system org owns runs
// unattended as the instance, so there it is the same administration as a
// control-plane resource. A schedule another org owns fires in that org, so
// there it is an ordinary org resource its members may create and update.
func scheduleRoute(r *http.Request, action access.Action, path string) (access.Action, access.ResourceKind, string, bool) {
if p, ok := access.PrincipalFromContext(r.Context()); ok && p.Org != org.DefaultOrgID {
return action, access.KindSchedule, segmentValue(path, 2), true
}
return actionManage(action), access.KindPolicy, segmentValue(path, 2), true
}
// controlPlaneResourceRoute maps a control-plane resource request. History
// returns the raw stored revisions, including secret references and policy
// text, because restore re-applies the real value: that is stronger than the
// redacted feed's read_audit grant, so it is policy management of that kind.
// Everything else falls back to the managed-resource action.
func controlPlaneResourceRoute(action access.Action, path string) (access.Action, access.ResourceKind, string, bool) {
if matchSegment(path, "/api/control-plane/resources/", "/history") {
return access.ActionManagePolicies, access.KindPolicy, segmentValue(path, 3), true
}
return actionManage(action), access.KindPolicy, segmentValue(path, 3), true
}
// bindingCommand maps a binding lifecycle route to its action: approving arms
// a binding, so it is approval; pausing and resuming change its state.
func bindingCommand(action access.Action, path string) (access.Action, bool) {
switch {
case action != access.ActionCreate:
return action, false
case matchSegment(path, "/api/bindings/", "/approve"):
return access.ActionApprove, true
case matchSegment(path, "/api/bindings/", "/pause"), matchSegment(path, "/api/bindings/", "/resume"):
return access.ActionUpdate, true
}
return action, false
}
// orgRouteAction maps an org request: reads are org reads, changing who
// belongs to the org or which agents serve it is member management (an
// admin's grant), and any other mutation updates the org.
func orgRouteAction(action access.Action, path string) access.Action {
switch {
case action == access.ActionRead:
return access.ActionRead
case segmentValue(path, 3) == "members", segmentValue(path, 3) == "agents":
return access.ActionManageMembers
}
return access.ActionUpdate
}
// updateCommandRoute reports whether the request is one of the chat update
// commands, which act on the update object rather than running a workflow.
func updateCommandRoute(action access.Action, path string) bool {
return action == access.ActionCreate &&
(path == "/api/chat/update/install" || path == "/api/chat/update/defer")
}
// chatRoute maps a chat request: posting runs a workflow, anything else reads
// the dashboard.
func chatRoute(action access.Action) (access.Action, access.ResourceKind, string, bool) {
if action == access.ActionCreate {
return access.ActionRun, access.KindWorkflow, "", true
}
return access.ActionRead, access.KindDashboard, "", true
}
// kindOf maps a collection route onto the resource kind it addresses.
func kindOf(path string) access.ResourceKind {
switch {
case matchPrefix(path, "/api/tasks"):
return access.KindTask
case matchPrefix(path, "/api/event-types"):
return access.KindEventType
case matchPrefix(path, "/api/mappings"):
return access.KindMapping
case matchPrefix(path, "/api/bindings"):
return access.KindBinding
case matchPrefix(path, "/api/sources"):
return access.KindSource
case matchPrefix(path, "/api/work-requests"), matchPrefix(path, "/api/repositories"):
return access.KindTask
}
return access.KindDashboard
}
// accessRoute maps the access routes: policy management on the policies
// routes, and on the denials route the same read_audit grant the audit feed
// carries, which the shipped role policies give an org's admins and owners
// only -- denial records are the access trail's operator surface.
func accessRoute(action access.Action, path string) (access.Action, access.ResourceKind, string, bool) {
if matchPrefix(path, "/api/access/policies") {
return policyAction(action), access.KindPolicy, "", true
}
return access.ActionReadAudit, access.KindAudit, "", true
}
// policyAction lifts every write on the policy routes to manage_policies.
func policyAction(action access.Action) access.Action {
if action == access.ActionRead {
return action
}
return access.ActionManagePolicies
}
// actionManage lifts a create or update on a managed surface to the manage
// action the role vocabulary carries.
func actionManage(action access.Action) access.Action {
switch action {
case access.ActionCreate, access.ActionUpdate:
return access.ActionManageIdentities
case access.ActionDelete:
return access.ActionDelete
}
return action
}
// segmentValue returns the value of the n-th (0-based) segment of an API
// path, or "" when the path is shorter: /api/tasks/7/changes -> 7 is segment
// 2.
func segmentValue(path string, n int) string {
segments := splitPath(path)
if n < len(segments) {
return segments[n]
}
return ""
}
func splitPath(path string) []string {
var out []string
for segment := range strings.SplitSeq(path, "/") {
if segment != "" {
out = append(out, segment)
}
}
return out
}
func matchPrefix(path, prefix string) bool {
return strings.HasPrefix(path, prefix+"/") || path == prefix
}
func matchSegment(path, prefix, suffix string) bool {
return strings.HasPrefix(path, prefix) && strings.HasSuffix(path, suffix)
}
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
}
return "", "", false
}