Files
archie/internal/webui/authorize.go
T
sam 01b691142c chore(lint): drop nolint directives that suppress nothing
29 of 59 directives did nothing. Removing each one individually and
re-running the gate revealed no issue from any of them: 20 named gosec,
which is not enabled in .golangci.yml and never has been, plus 4 nilerr
in functions that return no error, 2 dupl where dupl reports nothing
repo-wide, and one each of contextcheck, nestif and unused. The funlen
name on settings.go:147 is gone for the same reason; its gocyclo and
cyclop names are both live.

The unused directive in webui/authorize.go sat on `var _ = slog.Default`,
a statement that only existed to keep the log/slog import alive. Both go.

The 30 remaining directives all suppress a real issue.
2026-10-08 23:29:19 +11:00

269 lines
9.8 KiB
Go

package webui
import (
"context"
"net/http"
"strings"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// authorize wraps h with the policy chain. Optional: a server with no
// Authorizer keeps the credential check as the whole gate, which is the
// documented behaviour of an install that has not built the chain.
func (s *Server) authorize(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if s.Access == nil {
h.ServeHTTP(w, r)
return
}
principal, err := s.requestPrincipal(r.Context())
if err != nil {
if wantsDocument(r) {
s.authPage(w, "Sign-in could not resolve your org.")
return
}
http.Error(w, "principal unavailable", http.StatusServiceUnavailable)
return
}
action, kind, id := accessRequest(r)
// 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 is likewise the record's, not the route's.
resource := access.Resource{Kind: kind, ID: id, Org: principal.Org}
decision := s.Access.Authorize(principal, action, resource, access.Context{})
if !decision.Allowed {
s.recordDenial(r.Context(), principal, action, resource, decision)
if wantsDocument(r) {
s.authPage(w, "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(org.WithOrg(access.WithPrincipal(r.Context(), principal), principal.Org)))
})
}
// 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.Error("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 a, kind, id, ok := routeOverride(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(action access.Action, path string) (access.Action, access.ResourceKind, string, bool) {
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/policies"):
return policyAction(action), access.KindPolicy, "", true
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/extensions"):
// Installing and enabling an extension runs a process on the host, so it
// is the same administration as editing a control-plane resource.
return actionManage(action), access.KindPolicy, segmentValue(path, 2), true
case matchPrefix(path, "/api/control-plane/resources"):
return actionManage(action), access.KindPolicy, segmentValue(path, 3), true
case matchPrefix(path, "/api/chat"):
return chatRoute(action)
case matchSegment(path, "/api/sources/", "/secret"):
return access.ActionUpdate, access.KindSecret, segmentValue(path, 2), true
case matchPrefix(path, "/api/harness/terminal"):
// Opening the setup terminal updates the binding's secret.
return access.ActionUpdate, access.KindSecret, "", true
case matchPrefix(path, "/api/harness/bindings"):
return access.ActionRead, access.KindSecret, "", true
case matchPrefix(path, "/api/channels/"):
return actionManage(action), access.KindDashboard, segmentValue(path, 2), true
case matchPrefix(path, "/api/config"), matchPrefix(path, "/api/logs"),
// A person's own tokens act only as that person, so managing them
// needs no more than reading the dashboard.
matchPrefix(path, "/api/tokens"):
return access.ActionRead, access.KindDashboard, "", true
}
return action, "", "", false
}
// 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
}
// 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"):
return access.KindTask
}
return access.KindDashboard
}
// actionManage lifts a create or update on a managed surface to the manage
// action the role vocabulary carries.
// 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
}
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)
}