Merge branch 'worktree-agent-a82ec64b6cc1a2809'
# Conflicts: # internal/app/archie/operations.go # modules/events/events.go # modules/governance/accounts_api.go # modules/governance/governance.go
This commit is contained in:
44 files changed
+1462
-266
No files matched your search
@@ -0,0 +1,113 @@
|
||||
package archie
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
)
|
||||
|
||||
// operator authenticates every request as an instance administrator.
|
||||
type operator struct{}
|
||||
|
||||
func (operator) Authenticate(ctx context.Context, _ *http.Request) (context.Context, bool, error) {
|
||||
return ctx, true, nil
|
||||
}
|
||||
|
||||
// refuses answers every Allow with err and records what it was asked.
|
||||
type refuses struct {
|
||||
err error
|
||||
asked []string
|
||||
}
|
||||
|
||||
func (r *refuses) Allow(_ context.Context, action, kind string) error {
|
||||
r.asked = append(r.asked, action+" "+kind)
|
||||
return r.err
|
||||
}
|
||||
|
||||
// publicOperations are the only operations a caller reaches without a
|
||||
// credential: sign-in, setup and the auth status the sign-in page reads.
|
||||
var publicOperations = []string{
|
||||
"begin-oidc-sign-in", "begin-passkey-sign-in", "finish-oidc-sign-in", "finish-passkey-sign-in",
|
||||
"get-auth-status", "recover-account", "set-up-account", "sign-in", "sign-out",
|
||||
}
|
||||
|
||||
var pathParam = regexp.MustCompile(`\{[^}]+\}`)
|
||||
|
||||
// TestEveryOperationIsAuthorized guards deny-by-default across every module's
|
||||
// routes. Each registered operation is either one of the named public
|
||||
// operations or declares a valid action and resource kind, and a request that
|
||||
// fails the grant, or that cannot be decided, is refused before its handler
|
||||
// runs. The handlers here have nothing behind them, so one that ran would
|
||||
// panic.
|
||||
func TestEveryOperationIsAuthorized(t *testing.T) {
|
||||
probe := &refuses{err: httpapi.ErrDenied}
|
||||
mux, api := emptyAPI(operator{}, probe)
|
||||
routes := httpapi.Routes(api)
|
||||
if len(routes) < 100 {
|
||||
t.Fatalf("only %d operations registered", len(routes))
|
||||
}
|
||||
|
||||
var public []string
|
||||
for _, route := range routes {
|
||||
if route.Access.IsPublic() {
|
||||
public = append(public, route.ID)
|
||||
continue
|
||||
}
|
||||
action, kind, ok := route.Access.Declared()
|
||||
if !ok {
|
||||
t.Errorf("%s declares no access", route.ID)
|
||||
continue
|
||||
}
|
||||
if err := governance.Action(action).Validate(); err != nil || kind == "" {
|
||||
t.Errorf("%s declares %q on %q", route.ID, action, kind)
|
||||
}
|
||||
}
|
||||
slices.Sort(public)
|
||||
if !slices.Equal(public, publicOperations) {
|
||||
t.Errorf("public operations = %v, want %v", public, publicOperations)
|
||||
}
|
||||
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
err error
|
||||
want int
|
||||
}{
|
||||
{"a failing grant", httpapi.ErrDenied, http.StatusForbidden},
|
||||
{"an unavailable policy chain", httpapi.ErrUnavailable, http.StatusServiceUnavailable},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
for _, route := range routes {
|
||||
action, kind, ok := route.Access.Declared()
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
probe.err, probe.asked = tt.err, nil
|
||||
req := httptest.NewRequestWithContext(t.Context(), route.Method, pathParam.ReplaceAllString(route.Path, "x"), nil)
|
||||
rec := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec, req)
|
||||
if rec.Code != tt.want {
|
||||
t.Errorf("%s: status = %d, want %d", route.ID, rec.Code, tt.want)
|
||||
}
|
||||
if want := []string{action + " " + kind}; !slices.Equal(probe.asked, want) {
|
||||
t.Errorf("%s: decided on %v, want %v", route.ID, probe.asked, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnwiredAuthorizerRefuses guards the boot order: until the policy chain
|
||||
// is wired, an authorized operation is refused rather than let through.
|
||||
func TestUnwiredAuthorizerRefuses(t *testing.T) {
|
||||
settings := &governance.Module{}
|
||||
if err := settings.Allow(governance.WithPrincipal(t.Context(), governance.SharedTokenOwner()), "read", "run"); !errors.Is(err, httpapi.ErrUnavailable) {
|
||||
t.Fatalf("Allow with no chain = %v, want %v", err, httpapi.ErrUnavailable)
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,15 @@ func (m apiModules) register(api huma.API) {
|
||||
// needs no database.
|
||||
func Document() ([]byte, error) {
|
||||
settings := &governance.Module{}
|
||||
api := httpapi.New(http.NewServeMux(), buildinfo.Version, settings.Authenticator(""))
|
||||
_, api := emptyAPI(settings.Authenticator(""), settings)
|
||||
return api.OpenAPI().YAML()
|
||||
}
|
||||
|
||||
// emptyAPI registers every route on modules with nothing behind them.
|
||||
func emptyAPI(auth httpapi.Authenticator, authz httpapi.Authorizer) (*http.ServeMux, huma.API) {
|
||||
mux := http.NewServeMux()
|
||||
settings := &governance.Module{}
|
||||
api := httpapi.New(mux, buildinfo.Version, auth, authz)
|
||||
apiModules{
|
||||
settings: settings, conns: &connectors.Module{}, system: &system.Module{},
|
||||
tell: &deliveries.Module{}, allow: &approvals.Module{}, classes: &judgement.Classes{},
|
||||
@@ -76,5 +84,5 @@ func Document() ([]byte, error) {
|
||||
engine: &runs.Engine{}, chat: &chat.Module{}, drafts: &drafts.Module{},
|
||||
notes: &memory.Module{}, live: hub.New(),
|
||||
}.register(api)
|
||||
return api.OpenAPI().YAML()
|
||||
return mux, api
|
||||
}
|
||||
@@ -55,11 +55,15 @@ func (o *operations) Start(ctx context.Context) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Every entry point asks the same chain, and each refusal is stored as a
|
||||
// denial.
|
||||
checked := governance.Recording(access, o.settings, o.log.With("module", "governance"))
|
||||
// A workflow takes its context from the run handle, as a handler takes it
|
||||
// from the request.
|
||||
o.engine.Use(runs.Deps{
|
||||
Settings: o.settings, Toolbox: o.conns, Judge: o.judge, Approver: o.allow,
|
||||
Notifier: o.tell, Messenger: o.tell, Memory: o.remember, Capabilities: o.conns,
|
||||
Access: checked,
|
||||
})
|
||||
if err := installStarter(ctx, o.engine); err != nil {
|
||||
return err
|
||||
@@ -76,10 +80,13 @@ func (o *operations) Start(ctx context.Context) error {
|
||||
|
||||
// Nothing below can fail, so a retry cannot launch a connector or a loop twice.
|
||||
o.checks.Register("connectors", o.conns.Ready)
|
||||
// Administrative writes are checked against the same live policy chain as
|
||||
// every other request.
|
||||
o.settings.UseAuthorizer(access)
|
||||
o.allow.UseAuthorizer(access)
|
||||
// Administrative writes, and every API request, are checked against the same
|
||||
// live policy chain as chat and background work. The webhook intake applies
|
||||
// each source's delivery policy from it.
|
||||
o.settings.UseAuthorizer(checked)
|
||||
o.allow.UseAuthorizer(checked)
|
||||
o.tell.UseAccess(checked)
|
||||
o.hear.UseDeliveryPolicy(access)
|
||||
o.talk.Use(chat.Deps{
|
||||
People: o.settings, Access: access, Settings: o.settings, Toolbox: o.conns, Judge: o.judge,
|
||||
Approver: o.allow, Memory: o.remember, Runs: o.engine, Notifier: o.tell,
|
||||
|
||||
@@ -151,7 +151,7 @@ func wire(log *slog.Logger, configPath string, cfg Config, db *sqlx.DB) (*binary
|
||||
runtime.RegisterBuiltinClasses()
|
||||
settings := governance.NewModule(db, log.With("module", "governance"), orgID)
|
||||
mux := http.NewServeMux()
|
||||
api := httpapi.New(mux, buildinfo.Version, settings.Authenticator(cfg.AdminTokenSHA256))
|
||||
api := httpapi.New(mux, buildinfo.Version, settings.Authenticator(cfg.AdminTokenSHA256), settings)
|
||||
|
||||
conns, err := connectors.NewModule(db, log.With("module", "connectors"), orgID, connectors.Sealing{
|
||||
Identity: cfg.AgeIdentity, Backups: cfg.AgeBackupRecipients,
|
||||
|
||||
@@ -43,50 +43,120 @@ func OK[T any](v T) *Reply[T] {
|
||||
return &Reply[T]{Body: v}
|
||||
}
|
||||
|
||||
type access int
|
||||
// ErrDenied is what an Authorizer returns when the caller's grant does not
|
||||
// cover the operation.
|
||||
var ErrDenied = errors.New("not permitted")
|
||||
|
||||
// ErrUnavailable is what an Authorizer returns when it cannot decide, such as
|
||||
// when the policy chain is not loaded. The operation is then refused.
|
||||
var ErrUnavailable = errors.New("authorization is unavailable")
|
||||
|
||||
// Authorizer decides whether the caller acting in ctx may take action on a
|
||||
// resource of kind. It returns ErrDenied, ErrUnavailable or nil.
|
||||
type Authorizer interface {
|
||||
Allow(ctx context.Context, action, kind string) error
|
||||
}
|
||||
|
||||
type accessKind int
|
||||
|
||||
const (
|
||||
accessAdmin access = iota
|
||||
accessSignedIn
|
||||
// accessUnset is the zero Access. An operation holding it is refused, so
|
||||
// an operation that declares nothing never runs.
|
||||
accessUnset accessKind = iota
|
||||
accessPublic
|
||||
accessAuthorized
|
||||
)
|
||||
|
||||
// Access is how an operation is guarded. Register requires one, and the zero
|
||||
// value refuses every request.
|
||||
type Access struct {
|
||||
kind accessKind
|
||||
action string
|
||||
resource string
|
||||
admin bool
|
||||
}
|
||||
|
||||
// Public is an operation callable without a credential: liveness, setup and
|
||||
// sign-in.
|
||||
func Public() Access { return Access{kind: accessPublic} }
|
||||
|
||||
// Authorized is an operation that needs an authenticated caller whose grant
|
||||
// covers action on a resource of kind, as the policy chain decides.
|
||||
func Authorized[A, K ~string](action A, kind K) Access {
|
||||
return Access{kind: accessAuthorized, action: string(action), resource: string(kind)}
|
||||
}
|
||||
|
||||
// AdminAuthorized is Authorized for an operation that also needs an instance
|
||||
// administrator, whatever the policy chain would allow.
|
||||
func AdminAuthorized[A, K ~string](action A, kind K) Access {
|
||||
a := Authorized(action, kind)
|
||||
a.admin = true
|
||||
return a
|
||||
}
|
||||
|
||||
// Declared reports the action and resource kind an authorized operation is
|
||||
// decided on, and false for any other operation.
|
||||
func (a Access) Declared() (action, kind string, ok bool) {
|
||||
return a.action, a.resource, a.kind == accessAuthorized
|
||||
}
|
||||
|
||||
// IsPublic reports whether the operation needs no credential.
|
||||
func (a Access) IsPublic() bool { return a.kind == accessPublic }
|
||||
|
||||
const accessKey = "archie-access"
|
||||
|
||||
// Public marks op as callable without a credential: signing in, for one.
|
||||
func Public(op huma.Operation) huma.Operation {
|
||||
op.Security = []map[string][]string{{}}
|
||||
return withAccess(op, accessPublic)
|
||||
}
|
||||
|
||||
// SignedIn marks op as callable by any authenticated caller. Every other
|
||||
// operation needs an instance administrator.
|
||||
func SignedIn(op huma.Operation) huma.Operation {
|
||||
return withAccess(op, accessSignedIn)
|
||||
}
|
||||
|
||||
func withAccess(op huma.Operation, a access) huma.Operation {
|
||||
// Register adds an operation guarded as access says. It is the only way to
|
||||
// register one on this API, so every operation declares who may call it.
|
||||
func Register[I, O any](api huma.API, access Access, op huma.Operation, handler func(context.Context, *I) (*O, error)) {
|
||||
if op.Metadata == nil {
|
||||
op.Metadata = map[string]any{}
|
||||
}
|
||||
op.Metadata[accessKey] = a
|
||||
return op
|
||||
op.Metadata[accessKey] = access
|
||||
if access.kind == accessPublic {
|
||||
op.Security = []map[string][]string{{}}
|
||||
}
|
||||
huma.Register(api, op, handler)
|
||||
}
|
||||
|
||||
func accessOf(op *huma.Operation) access {
|
||||
// AccessOf returns how a registered operation is guarded. An operation not
|
||||
// registered through Register has the zero Access.
|
||||
func AccessOf(op *huma.Operation) Access {
|
||||
if op == nil {
|
||||
return accessAdmin
|
||||
return Access{}
|
||||
}
|
||||
a, _ := op.Metadata[accessKey].(access)
|
||||
a, _ := op.Metadata[accessKey].(Access)
|
||||
return a
|
||||
}
|
||||
|
||||
// Route is a registered operation and how it is guarded.
|
||||
type Route struct {
|
||||
ID, Method, Path string
|
||||
Access Access
|
||||
}
|
||||
|
||||
// Routes returns every operation registered on api with how it is guarded.
|
||||
func Routes(api huma.API) []Route {
|
||||
var out []Route
|
||||
for p, item := range api.OpenAPI().Paths {
|
||||
for method, op := range map[string]*huma.Operation{
|
||||
http.MethodGet: item.Get, http.MethodPut: item.Put, http.MethodPost: item.Post,
|
||||
http.MethodDelete: item.Delete, http.MethodPatch: item.Patch, http.MethodHead: item.Head,
|
||||
http.MethodOptions: item.Options, http.MethodTrace: item.Trace,
|
||||
} {
|
||||
if op != nil {
|
||||
out = append(out, Route{ID: op.OperationID, Method: method, Path: p, Access: AccessOf(op)})
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// New returns an API on mux whose operations authenticate through auth.
|
||||
// Every unsafe request must also pass cross-origin protection, since a
|
||||
// browser sends the session cookie with any request to this origin.
|
||||
func New(mux *http.ServeMux, version string, auth Authenticator) huma.API {
|
||||
func New(mux *http.ServeMux, version string, auth Authenticator, authz Authorizer) huma.API {
|
||||
api := humago.New(mux, config(version))
|
||||
api.UseMiddleware(guard(api, auth, http.NewCrossOriginProtection()))
|
||||
api.UseMiddleware(guard(api, auth, authz, http.NewCrossOriginProtection()))
|
||||
return api
|
||||
}
|
||||
|
||||
@@ -106,17 +176,22 @@ func config(version string) huma.Config {
|
||||
return cfg
|
||||
}
|
||||
|
||||
func guard(api huma.API, auth Authenticator, origins *http.CrossOriginProtection) func(huma.Context, func(huma.Context)) {
|
||||
func guard(api huma.API, auth Authenticator, authz Authorizer, origins *http.CrossOriginProtection) func(huma.Context, func(huma.Context)) {
|
||||
return func(ctx huma.Context, next func(huma.Context)) {
|
||||
r, _ := humago.Unwrap(ctx)
|
||||
if err := origins.Check(r); err != nil {
|
||||
_ = huma.WriteErr(api, ctx, http.StatusForbidden, "cross-origin request refused")
|
||||
return
|
||||
}
|
||||
need := accessOf(ctx.Operation())
|
||||
if need == accessPublic {
|
||||
need := AccessOf(ctx.Operation())
|
||||
switch need.kind {
|
||||
case accessPublic:
|
||||
next(ctx)
|
||||
return
|
||||
case accessAuthorized:
|
||||
default:
|
||||
_ = huma.WriteErr(api, ctx, http.StatusForbidden, "operation declares no access")
|
||||
return
|
||||
}
|
||||
acting, admin, err := auth.Authenticate(ctx.Context(), r)
|
||||
switch {
|
||||
@@ -127,14 +202,35 @@ func guard(api huma.API, auth Authenticator, origins *http.CrossOriginProtection
|
||||
case err != nil:
|
||||
_ = huma.WriteErr(api, ctx, http.StatusServiceUnavailable, "authentication is unavailable")
|
||||
return
|
||||
case need == accessAdmin && !admin:
|
||||
case need.admin && !admin:
|
||||
_ = huma.WriteErr(api, ctx, http.StatusForbidden, "instance administrator required")
|
||||
return
|
||||
}
|
||||
if status, msg := decide(acting, authz, need); status != 0 {
|
||||
_ = huma.WriteErr(api, ctx, status, msg)
|
||||
return
|
||||
}
|
||||
next(huma.WithContext(ctx, acting))
|
||||
}
|
||||
}
|
||||
|
||||
// decide asks authz whether the authenticated caller may take the declared
|
||||
// action. It returns a status of 0 to let the request through. With no
|
||||
// authorizer the operation is refused.
|
||||
func decide(acting context.Context, authz Authorizer, need Access) (status int, message string) {
|
||||
if authz == nil {
|
||||
return http.StatusServiceUnavailable, ErrUnavailable.Error()
|
||||
}
|
||||
switch err := authz.Allow(acting, need.action, need.resource); {
|
||||
case err == nil:
|
||||
return 0, ""
|
||||
case errors.Is(err, ErrDenied):
|
||||
return http.StatusForbidden, ErrDenied.Error()
|
||||
default:
|
||||
return http.StatusServiceUnavailable, ErrUnavailable.Error()
|
||||
}
|
||||
}
|
||||
|
||||
// schemaName prefixes a type of Archie's own with its package, since modules
|
||||
// reuse short names like Source and Request.
|
||||
func schemaName(t reflect.Type, hint string) string {
|
||||
|
||||
@@ -26,46 +26,88 @@ func (headerAuth) Authenticate(ctx context.Context, r *http.Request) (context.Co
|
||||
}
|
||||
}
|
||||
|
||||
// TestOperationAccess guards the API's authentication boundary: public
|
||||
// operations need no credential, every other operation needs one, only an
|
||||
// instance administrator reaches an operation not marked otherwise, and a
|
||||
// cross-origin browser request cannot use the session cookie to change
|
||||
// anything.
|
||||
// grants answers Allow from a fixed set of "action kind" pairs and records
|
||||
// what it was asked.
|
||||
type grants struct {
|
||||
allowed map[string]bool
|
||||
err error
|
||||
asked []string
|
||||
}
|
||||
|
||||
func (g *grants) Allow(_ context.Context, action, kind string) error {
|
||||
g.asked = append(g.asked, action+" "+kind)
|
||||
switch {
|
||||
case g.err != nil:
|
||||
return g.err
|
||||
case g.allowed[action+" "+kind]:
|
||||
return nil
|
||||
}
|
||||
return ErrDenied
|
||||
}
|
||||
|
||||
// TestOperationAccess guards the API's enforcement boundary: public
|
||||
// operations need no credential, every other operation needs one and a grant
|
||||
// from the authorizer before its handler runs, an operation that declares no
|
||||
// access never runs, and a cross-origin browser request cannot use the
|
||||
// session cookie to change anything.
|
||||
func TestOperationAccess(t *testing.T) {
|
||||
tests := []struct {
|
||||
name, method, path, caller, fetchSite string
|
||||
grants *grants
|
||||
noAuthorizer bool
|
||||
want int
|
||||
wantRan bool
|
||||
}{
|
||||
{name: "public without a credential", method: http.MethodGet, path: "/public", want: http.StatusOK},
|
||||
{name: "public sign-in from this origin", method: http.MethodPost, path: "/public", fetchSite: "same-origin", want: http.StatusOK},
|
||||
{name: "public without a credential", method: http.MethodGet, path: "/public", want: http.StatusOK, wantRan: true},
|
||||
{name: "public sign-in from this origin", method: http.MethodPost, path: "/public", fetchSite: "same-origin", want: http.StatusOK, wantRan: true},
|
||||
{name: "public sign-in from another origin", method: http.MethodPost, path: "/public", fetchSite: "cross-site", want: http.StatusForbidden},
|
||||
{name: "signed-in without a credential", method: http.MethodGet, path: "/signed-in", want: http.StatusUnauthorized},
|
||||
{name: "signed-in as a person", method: http.MethodGet, path: "/signed-in", caller: "person", want: http.StatusOK},
|
||||
{name: "a stream without a credential", method: http.MethodGet, path: "/stream", want: http.StatusUnauthorized},
|
||||
{name: "a stream as a person", method: http.MethodGet, path: "/stream", caller: "person", want: http.StatusOK},
|
||||
{name: "admin without a credential", method: http.MethodGet, path: "/admin", want: http.StatusUnauthorized},
|
||||
{name: "admin as a person", method: http.MethodGet, path: "/admin", caller: "person", want: http.StatusForbidden},
|
||||
{name: "admin as the admin", method: http.MethodGet, path: "/admin", caller: "admin", want: http.StatusOK},
|
||||
{name: "mutation from this origin", method: http.MethodPost, path: "/admin", caller: "admin", fetchSite: "same-origin", want: http.StatusOK},
|
||||
{name: "mutation from another origin", method: http.MethodPost, path: "/admin", caller: "admin", fetchSite: "cross-site", want: http.StatusForbidden},
|
||||
{name: "a failed lookup is not a refusal", method: http.MethodGet, path: "/admin", caller: "broken", want: http.StatusServiceUnavailable},
|
||||
{name: "authorized without a credential", method: http.MethodGet, path: "/read", want: http.StatusUnauthorized},
|
||||
{name: "authorized and granted", method: http.MethodGet, path: "/read", caller: "person", grants: &grants{allowed: map[string]bool{"read thing": true}}, want: http.StatusOK, wantRan: true},
|
||||
{name: "authorized but not granted", method: http.MethodGet, path: "/read", caller: "person", grants: &grants{}, want: http.StatusForbidden},
|
||||
{name: "authorized while the chain is unavailable", method: http.MethodGet, path: "/read", caller: "person", grants: &grants{err: ErrUnavailable}, want: http.StatusServiceUnavailable},
|
||||
{name: "authorized when the authorizer fails", method: http.MethodGet, path: "/read", caller: "person", grants: &grants{err: errors.New("database down")}, want: http.StatusServiceUnavailable},
|
||||
{name: "authorized with no authorizer", method: http.MethodGet, path: "/read", caller: "admin", noAuthorizer: true, want: http.StatusServiceUnavailable},
|
||||
{name: "a stream not granted", method: http.MethodGet, path: "/stream", caller: "person", grants: &grants{}, want: http.StatusForbidden},
|
||||
{name: "a stream granted", method: http.MethodGet, path: "/stream", caller: "person", grants: &grants{allowed: map[string]bool{"read thing": true}}, want: http.StatusOK, wantRan: true},
|
||||
{name: "admin operation as a person with the grant", method: http.MethodGet, path: "/admin", caller: "person", grants: &grants{allowed: map[string]bool{"update thing": true}}, want: http.StatusForbidden},
|
||||
{name: "admin operation as the admin without the grant", method: http.MethodGet, path: "/admin", caller: "admin", grants: &grants{}, want: http.StatusForbidden},
|
||||
{name: "admin operation as the admin with the grant", method: http.MethodGet, path: "/admin", caller: "admin", grants: &grants{allowed: map[string]bool{"update thing": true}}, want: http.StatusOK, wantRan: true},
|
||||
{name: "an operation that declares nothing", method: http.MethodGet, path: "/undeclared", caller: "admin", grants: &grants{allowed: map[string]bool{" ": true}}, want: http.StatusForbidden},
|
||||
{name: "mutation from this origin", method: http.MethodPost, path: "/admin", caller: "admin", fetchSite: "same-origin", grants: &grants{allowed: map[string]bool{"update thing": true}}, want: http.StatusOK, wantRan: true},
|
||||
{name: "mutation from another origin", method: http.MethodPost, path: "/admin", caller: "admin", fetchSite: "cross-site", grants: &grants{allowed: map[string]bool{"update thing": true}}, want: http.StatusForbidden},
|
||||
{name: "a failed lookup is not a refusal", method: http.MethodGet, path: "/read", caller: "broken", grants: &grants{}, want: http.StatusServiceUnavailable},
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
api := New(mux, "test", headerAuth{})
|
||||
reached := func(context.Context, *struct{}) (*Reply[string], error) { return OK("reached"), nil }
|
||||
for _, method := range []string{http.MethodGet, http.MethodPost} {
|
||||
huma.Register(api, Public(huma.Operation{OperationID: "public-" + method, Method: method, Path: "/public"}), reached)
|
||||
huma.Register(api, SignedIn(huma.Operation{OperationID: "signed-in-" + method, Method: method, Path: "/signed-in"}), reached)
|
||||
huma.Register(api, huma.Operation{OperationID: "admin-" + method, Method: method, Path: "/admin"}, reached)
|
||||
}
|
||||
// A streamed response writes its own status, so it must still pass the
|
||||
// guard before its body runs.
|
||||
huma.Register(api, SignedIn(huma.Operation{OperationID: "stream", Method: http.MethodGet, Path: "/stream"}),
|
||||
func(context.Context, *struct{}) (*huma.StreamResponse, error) {
|
||||
return &huma.StreamResponse{Body: func(hc huma.Context) { hc.SetStatus(http.StatusOK) }}, nil
|
||||
})
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
var authz Authorizer
|
||||
if !tt.noAuthorizer {
|
||||
if tt.grants == nil {
|
||||
tt.grants = &grants{}
|
||||
}
|
||||
authz = tt.grants
|
||||
}
|
||||
api := New(mux, "test", headerAuth{}, authz)
|
||||
ran := false
|
||||
reached := func(context.Context, *struct{}) (*Reply[string], error) {
|
||||
ran = true
|
||||
return OK("reached"), nil
|
||||
}
|
||||
for _, method := range []string{http.MethodGet, http.MethodPost} {
|
||||
Register(api, Public(), huma.Operation{OperationID: "public-" + method, Method: method, Path: "/public"}, reached)
|
||||
Register(api, Authorized("read", "thing"), huma.Operation{OperationID: "read-" + method, Method: method, Path: "/read"}, reached)
|
||||
Register(api, AdminAuthorized("update", "thing"), huma.Operation{OperationID: "admin-" + method, Method: method, Path: "/admin"}, reached)
|
||||
// A direct huma registration declares no access.
|
||||
huma.Register(api, huma.Operation{OperationID: "undeclared-" + method, Method: method, Path: "/undeclared"}, reached)
|
||||
}
|
||||
// A streamed response writes its own status, so it must still pass
|
||||
// the guard before its body runs.
|
||||
Register(api, Authorized("read", "thing"), huma.Operation{OperationID: "stream", Method: http.MethodGet, Path: "/stream"},
|
||||
func(context.Context, *struct{}) (*huma.StreamResponse, error) {
|
||||
ran = true
|
||||
return &huma.StreamResponse{Body: func(hc huma.Context) { hc.SetStatus(http.StatusOK) }}, nil
|
||||
})
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), tt.method, tt.path, nil)
|
||||
if tt.caller != "" {
|
||||
req.Header.Set("X-Test-Caller", tt.caller)
|
||||
@@ -78,6 +120,34 @@ func TestOperationAccess(t *testing.T) {
|
||||
if rec.Code != tt.want {
|
||||
t.Fatalf("status = %d, want %d: %s", rec.Code, tt.want, rec.Body)
|
||||
}
|
||||
if ran != tt.wantRan {
|
||||
t.Fatalf("handler ran = %v, want %v", ran, tt.wantRan)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestOperationsDeclareAccess guards the registry the route table is checked
|
||||
// from: an operation registered through Register reports what it declared, and
|
||||
// one registered directly reports none.
|
||||
func TestOperationsDeclareAccess(t *testing.T) {
|
||||
api := New(http.NewServeMux(), "test", headerAuth{}, nil)
|
||||
noop := func(context.Context, *struct{}) (*Reply[string], error) { return OK(""), nil }
|
||||
Register(api, Public(), huma.Operation{OperationID: "p", Method: http.MethodGet, Path: "/p"}, noop)
|
||||
Register(api, Authorized("read", "thing"), huma.Operation{OperationID: "a", Method: http.MethodGet, Path: "/a"}, noop)
|
||||
huma.Register(api, huma.Operation{OperationID: "u", Method: http.MethodGet, Path: "/u"}, noop)
|
||||
|
||||
got := map[string]Access{}
|
||||
for _, r := range Routes(api) {
|
||||
got[r.ID] = r.Access
|
||||
}
|
||||
if !got["p"].IsPublic() {
|
||||
t.Error("p is not public")
|
||||
}
|
||||
if action, kind, ok := got["a"].Declared(); !ok || action != "read" || kind != "thing" {
|
||||
t.Errorf("a declares %q %q %v", action, kind, ok)
|
||||
}
|
||||
if _, _, ok := got["u"].Declared(); ok || got["u"].IsPublic() {
|
||||
t.Error("u declares access it never registered")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user