package httpapi import ( "context" "errors" "net/http" "net/http/httptest" "testing" "github.com/danielgtaylor/huma/v2" ) // headerAuth admits the caller its X-Test-Caller header names. type headerAuth struct{} func (headerAuth) Authenticate(ctx context.Context, r *http.Request) (context.Context, bool, error) { switch r.Header.Get("X-Test-Caller") { case "admin": return ctx, true, nil case "person": return ctx, false, nil case "broken": return nil, false, errors.New("database down") default: return nil, false, ErrUnauthenticated } } // 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, 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: "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}, } 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) } if tt.fetchSite != "" { req.Header.Set("Sec-Fetch-Site", tt.fetchSite) } rec := httptest.NewRecorder() mux.ServeHTTP(rec, req) 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") } }