diff --git a/http/server/api.go b/http/server/api.go index 951c8e0..a27e6a2 100644 --- a/http/server/api.go +++ b/http/server/api.go @@ -4,29 +4,73 @@ import ( "fmt" "github.com/dioad/auth" + "github.com/dioad/net/authz" nethttp "github.com/dioad/net/http" + "github.com/dioad/auth/http/authz/principal" "github.com/dioad/auth/http/middleware" "github.com/dioad/auth/oidc" ) +// APIOption configures APIMiddlewares. A ValidatorHandlerOption is an +// APIOption that configures the token validation step. +type APIOption interface { + applyAPI(*apiOptions) +} + +type apiOptions struct { + validator []ValidatorHandlerOption + acl *authz.PrincipalACLConfig +} + +func (o ValidatorHandlerOption) applyAPI(a *apiOptions) { + a.validator = append(a.validator, o) +} + +type apiOptionFunc func(*apiOptions) + +func (f apiOptionFunc) applyAPI(a *apiOptions) { f(a) } + +// WithPrincipalACL adds a last step that admits only the principals acl +// allows, by the subject of the validated token, and refuses those it denies. +// It is for an API that authorises by who the caller is rather than by role, +// for example one that always admits the owner of a resource. It needs a +// token validated ahead of it, so use it with validators. +func WithPrincipalACL(acl authz.PrincipalACLConfig) APIOption { + return apiOptionFunc(func(a *apiOptions) { a.acl = &acl }) +} + // APIMiddlewares returns the authentication half of an API's middleware // chain, in order: bearer token validation against validators, then principal -// extraction with extractor. Token validation is left out when there are no -// validators, which is the allow-unauthenticated case, so every request -// reaches the principal extractor with no token. +// extraction with extractor, then, with WithPrincipalACL, the principal ACL. +// Token validation is left out when there are no validators, which is the +// allow-unauthenticated case, so every request reaches the principal extractor +// with no token. A nil extractor leaves extraction out, for an API that +// authorises with WithPrincipalACL and has no roles to extract. // -// Put anything that must run before authentication, such as a header check, -// ahead of the result, and anything that needs the principal, such as a rate -// limiter keyed by principal, after it. opts are passed to OAuth2ValidatorHandler. -func APIMiddlewares(validators []oidc.ValidatorConfig, extractor auth.PrincipalExtractor, opts ...ValidatorHandlerOption) ([]nethttp.Middleware, error) { +// Put anything that must run before authentication, such as a header check or +// CORS, ahead of the result, and anything that needs the principal, such as a +// rate limiter keyed by principal, after it. Options that are +// ValidatorHandlerOptions are passed to OAuth2ValidatorHandler. +func APIMiddlewares(validators []oidc.ValidatorConfig, extractor auth.PrincipalExtractor, opts ...APIOption) ([]nethttp.Middleware, error) { + var options apiOptions + for _, opt := range opts { + opt.applyAPI(&options) + } + var chain []nethttp.Middleware if len(validators) > 0 { - validate, err := OAuth2ValidatorHandler(validators, opts...) + validate, err := OAuth2ValidatorHandler(validators, options.validator...) if err != nil { return nil, fmt.Errorf("building JWT middleware: %w", err) } chain = append(chain, validate) } - return append(chain, middleware.PrincipalExtractionHandler(extractor)), nil + if extractor != nil { + chain = append(chain, middleware.PrincipalExtractionHandler(extractor)) + } + if options.acl != nil { + chain = append(chain, principal.NewHandler(*options.acl).Wrap) + } + return chain, nil } diff --git a/http/server/api_test.go b/http/server/api_test.go index 1a4ed74..a1262dc 100644 --- a/http/server/api_test.go +++ b/http/server/api_test.go @@ -9,8 +9,10 @@ import ( "github.com/stretchr/testify/require" "github.com/dioad/auth" + "github.com/dioad/auth/authctx" "github.com/dioad/auth/http/server" "github.com/dioad/auth/oidc" + "github.com/dioad/net/authz" nethttp "github.com/dioad/net/http" ) @@ -53,3 +55,52 @@ func TestAPIMiddlewares_ReportsAnInvalidValidator(t *testing.T) { assert.ErrorContains(t, err, "building JWT middleware") } + +func TestAPIMiddlewares_WithoutAnExtractorLeavesExtractionOut(t *testing.T) { + t.Parallel() + + chain, err := server.APIMiddlewares(nil, nil) + require.NoError(t, err) + + assert.Empty(t, chain) +} + +func TestAPIMiddlewares_PrincipalACLAdmitsOnlyWhatItAllows(t *testing.T) { + t.Parallel() + + acl := authz.PrincipalACLConfig{AllowList: []string{"owner@example.com"}, DenyList: []string{"banned@example.com"}} + chain, err := server.APIMiddlewares(nil, nil, server.WithPrincipalACL(acl)) + require.NoError(t, err) + require.Len(t, chain, 1) + + tests := []struct { + principal string + want int + }{ + {"owner@example.com", http.StatusNoContent}, + {"stranger@example.com", http.StatusForbidden}, + {"banned@example.com", http.StatusForbidden}, + } + for _, tc := range tests { + t.Run(tc.principal, func(t *testing.T) { + t.Parallel() + + req := httptest.NewRequestWithContext(authctx.ContextWithAuthenticatedPrincipal(t.Context(), tc.principal), http.MethodGet, "/", nil) + + assert.Equal(t, tc.want, serve(t, chain, req).Code) + }) + } +} + +func TestAPIMiddlewares_PrincipalACLRunsAfterValidationAndExtraction(t *testing.T) { + t.Parallel() + + validators := []oidc.ValidatorConfig{{Issuer: "https://issuer.example", HMACSecret: "0123456789abcdef0123456789abcdef", AllowInsecureHMAC: true}} + chain, err := server.APIMiddlewares(validators, auth.NewAllowAllPrincipalExtractor(), + server.WithCookieTokenName("session"), server.WithPrincipalACL(authz.PrincipalACLConfig{})) + require.NoError(t, err) + + assert.Len(t, chain, 3) + rec := serve(t, chain, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil)) + assert.Equal(t, http.StatusUnauthorized, rec.Code, "a request with no token never reaches the ACL") +}