Files

53 lines
1.9 KiB
Go

package gateway
import (
"context"
"errors"
"fmt"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/tools"
)
// guarded makes entry ask the access policies before it runs, as the caller
// the context carries: the person chatting, or a task's identity. It asks with
// the action and resource the dashboard asks for the same request, so a tool
// never reaches further than its caller could through the dashboard. A
// context with no principal is refused, and so is a chain that cannot be
// read -- reported as unavailable rather than as a permission the caller
// lacks.
func guarded(authz access.Authorizer, action access.Action, kind access.ResourceKind, id func(map[string]any) string, entry tools.ToolEntry) tools.ToolEntry {
handler := entry.Handler
entry.Handler = func(ctx context.Context, input map[string]any) (any, error) {
p, ok := access.PrincipalFromContext(ctx)
if !ok {
return nil, fmt.Errorf("%s: no caller to authorize", entry.Name)
}
resource := access.Resource{Kind: kind}
if id != nil {
resource.ID = id(input)
}
decision := authz.Authorize(ctx, p, action, resource, access.Context{})
if decision.Allowed {
return handler(ctx, input)
}
if errors.Is(decision.Err, access.ErrChainUnavailable) {
// Nothing was evaluated. Telling the caller it may not do this would
// send it looking for a permission it already holds.
return nil, fmt.Errorf("%s: access policies unavailable, retry shortly", entry.Name)
}
return nil, fmt.Errorf("%s: %s may not %s this %s", entry.Name, p.IdentityID, action, kind)
}
return entry
}
// fixedID names the same record for every call.
func fixedID(id string) func(map[string]any) string {
return func(map[string]any) string { return id }
}
// inputID names the record the call's input names.
func inputID(key string) func(map[string]any) string {
return func(input map[string]any) string { return asString(input[key]) }
}