Repository: go-openapi/runtime
Pull request #275 (2023-12-08 15:37:39)

test: refact tests for authenticators


Patch:
diff --git a/client/keepalive.go b/client/keepalive.go
index bc7b7fa..7dd6b51 100644
--- a/client/keepalive.go
+++ b/client/keepalive.go
@@ -48,8 +48,7 @@ func (d *drainingReadCloser) Close() error {
 		// If the reader side (a HTTP server) is misbehaving, it still may send
 		// some bytes, but the closer ignores them to keep the underling
 		// connection open.
-		//nolint:errcheck
-		io.Copy(io.Discard, d.rdr)
+		_, _ = io.Copy(io.Discard, d.rdr)
 	}
 	return d.rdr.Close()
 }
diff --git a/client/request.go b/client/request.go
index 8b43386..65ef829 100644
--- a/client/request.go
+++ b/client/request.go
@@ -16,6 +16,7 @@ package client
 
 import (
 	"bytes"
+	"context"
 	"fmt"
 	"io"
 	"log"
@@ -317,13 +318,13 @@ DoneChoosingBodySource:
 
 	urlPath := path.Join(basePathURL.Path, pathPatternURL.Path)
 	for k, v := range r.pathParams {
-		urlPath = strings.Replace(urlPath, "{"+k+"}", url.PathEscape(v), -1) //nolint:gocritic
+		urlPath = strings.ReplaceAll(urlPath, "{"+k+"}", url.PathEscape(v))
 	}
 	if reinstateSlash {
-		urlPath = urlPath + "/" //nolint:gocritic
+		urlPath += "/"
 	}
 
-	req, err := http.NewRequest(r.method, urlPath, body) //nolint:noctx
+	req, err := http.NewRequestWithContext(context.Background(), r.method, urlPath, body)
 	if err != nil {
 		return nil, err
 	}
@@ -361,7 +362,7 @@ func (r *request) GetMethod() string {
 func (r *request) GetPath() string {
 	path := r.pathPattern
 	for k, v := range r.pathParams {
-		path = strings.Replace(path, "{"+k+"}", v, -1) //nolint:gocritic
+		path = strings.ReplaceAll(path, "{"+k+"}", v)
 	}
 	return path
 }
diff --git a/client/runtime.go b/client/runtime.go
index 629866b..8d293a5 100644
--- a/client/runtime.go
+++ b/client/runtime.go
@@ -12,7 +12,6 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-//nolint:goconst
 package client
 
 import (
@@ -40,6 +39,11 @@ import (
 	"github.com/opentracing/opentracing-go"
 )
 
+const (
+	schemeHTTP  = "http"
+	schemeHTTPS = "https"
+)
+
 // TLSClientOptions to configure client authentication with mutual TLS
 type TLSClientOptions struct {
 	// Certificate is the path to a PEM-encoded certificate to be used for
@@ -112,7 +116,9 @@ type TLSClientOptions struct {
 // TLSClientAuth creates a tls.Config for mutual auth
 func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) {
 	// create client tls config
-	cfg := &tls.Config{} //nolint:gosec
+	cfg := &tls.Config{
+		MinVersion: tls.VersionTLS12,
+	}
 
 	// load client cert if specified
 	if opts.Certificate != "" {
@@ -158,11 +164,12 @@ func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) {
 	// When no CA certificate is provided, default to the system cert pool
 	// that way when a request is made to a server known by the system trust store,
 	// the name is still verified
-	if opts.LoadedCA != nil { //nolint:gocritic
+	switch {
+	case opts.LoadedCA != nil:
 		caCertPool := basePool(opts.LoadedCAPool)
 		caCertPool.AddCert(opts.LoadedCA)
 		cfg.RootCAs = caCertPool
-	} else if opts.CA != "" {
+	case opts.CA != "":
 		// load ca cert
 		caCert, err := os.ReadFile(opts.CA)
 		if err != nil {
@@ -171,7 +178,7 @@ func TLSClientAuth(opts TLSClientOptions) (*tls.Config, error) {
 		caCertPool := basePool(opts.LoadedCAPool)
 		caCertPool.AppendCertsFromPEM(caCert)
 		cfg.RootCAs = caCertPool
-	} else if opts.LoadedCAPool != nil {
+	case opts.LoadedCAPool != nil:
 		cfg.RootCAs = opts.LoadedCAPool
 	}
 
@@ -227,7 +234,7 @@ type Runtime struct {
 	Host     string
 	BasePath string
 	Formats  strfmt.Registry
-	Context  context.Context //nolint:containedctx
+	Context  context.Context //nolint:containedctx  // we precisely want this type to contain the request context
 
 	Debug  bool
 	logger logger.Logger
@@ -316,7 +323,7 @@ func (r *Runtime) pickScheme(schemes []string) string {
 	if v := r.selectScheme(schemes); v != "" {
 		return v
 	}
-	return "http"
+	return schemeHTTP
 }
 
 func (r *Runtime) selectScheme(schemes []string) string {
@@ -327,9 +334,9 @@ func (r *Runtime) selectScheme(schemes []string) string {
 
 	scheme := schemes[0]
 	// prefer https, but skip when not possible
-	if scheme != "https" && schLen > 1 {
+	if scheme != schemeHTTPS && schLen > 1 {
 		for _, sch := range schemes {
-			if sch == "https" {
+			if sch == schemeHTTPS {
 				scheme = sch
 				break
 			}
diff --git a/client_operation.go b/client_operation.go
index 1a1975f..5a5d635 100644
--- a/client_operation.go
+++ b/client_operation.go
@@ -30,7 +30,7 @@ type ClientOperation struct {
 	AuthInfo           ClientAuthInfoWriter
 	Params             ClientRequestWriter
 	Reader             ClientResponseReader
-	Context            context.Context //nolint:containedctx
+	Context            context.Context //nolint:containedctx // we precisely want this type to contain the request context
 	Client             *http.Client
 }
 
diff --git a/client_request.go b/client_request.go
index 654333a..4ebb2de 100644
--- a/client_request.go
+++ b/client_request.go
@@ -37,10 +37,8 @@ type ClientRequestWriter interface {
 }
 
 // ClientRequest is an interface for things that know how to
-// add information to a swagger client request
-//
-//nolint:interfacebloat
-type ClientRequest interface {
+// add information to a swagger client request.
+type ClientRequest interface { //nolint:interfacebloat // a swagger-capable request is quite rich, hence the many getter/setters
 	SetHeaderParam(string, ...string) error
 
 	GetHeaderParams() http.Header
diff --git a/middleware/context.go b/middleware/context.go
index f68b751..d890ed3 100644
--- a/middleware/context.go
+++ b/middleware/context.go
@@ -12,7 +12,6 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-//nolint:goconst
 package middleware
 
 import (
@@ -517,7 +516,7 @@ func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []st
 			prods := c.api.ProducersFor(normalizeOffers([]string{c.api.DefaultProduces()}))
 			pr, ok := prods[c.api.DefaultProduces()]
 			if !ok {
-				panic(errors.New(http.StatusInternalServerError, "can't find a producer for "+format))
+				panic(errors.New(http.StatusInternalServerError, cantFindProducer(format)))
 			}
 			prod = pr
 		}
@@ -550,7 +549,7 @@ func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []st
 		producers := c.api.ProducersFor(normalizeOffers(offers))
 		prod, ok := producers[format]
 		if !ok {
-			panic(errors.New(http.StatusInternalServerError, "can't find a producer for "+format))
+			panic(errors.New(http.StatusInternalServerError, cantFindProducer(format)))
 		}
 		if err := prod.Produce(rw, data); err != nil {
 			panic(err) // let the recovery middleware deal with this
@@ -571,7 +570,7 @@ func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []st
 				prods := c.api.ProducersFor(normalizeOffers([]string{c.api.DefaultProduces()}))
 				pr, ok := prods[c.api.DefaultProduces()]
 				if !ok {
-					panic(errors.New(http.StatusInternalServerError, "can't find a producer for "+format))
+					panic(errors.New(http.StatusInternalServerError, cantFindProducer(format)))
 				}
 				prod = pr
 			}
@@ -634,3 +633,7 @@ func (c *Context) RoutesHandler(builder Builder) http.Handler {
 	}
 	return NewRouter(c, b(NewOperationExecutor(c)))
 }
+
+func cantFindProducer(format string) string {
+	return "can't find a producer for " + format
+}
diff --git a/middleware/denco/router.go b/middleware/denco/router.go
index 2ddd2f9..1bfa5c6 100644
--- a/middleware/denco/router.go
+++ b/middleware/denco/router.go
@@ -51,7 +51,7 @@ func New() *Router {
 // params is a slice of the Param that arranged in the order in which parameters appeared.
 // e.g. when built routing path is "/path/to/:id/:name" and given path is "/path/to/1/alice". params order is [{"id": "1"}, {"name": "alice"}], not [{"name": "alice"}, {"id": "1"}].
 func (rt *Router) Lookup(path string) (data interface{}, params Params, found bool) {
-	if data, found := rt.static[path]; found { //nolint:govet
+	if data, found = rt.static[path]; found {
 		return data, nil, true
 	}
 	if len(rt.param.node) == 1 {
diff --git a/middleware/header/header.go b/middleware/header/header.go
index 1923fa5..df073c8 100644
--- a/middleware/header/header.go
+++ b/middleware/header/header.go
@@ -195,9 +195,8 @@ func ParseAccept2(header http.Header, key string) (specs []AcceptSpec) {
 }
 
 // ParseAccept parses Accept* headers.
-//
-//nolint:nakedret
-func ParseAccept(header http.Header, key string) (specs []AcceptSpec) {
+func ParseAccept(header http.Header, key string) []AcceptSpec {
+	var specs []AcceptSpec
 loop:
 	for _, s := range header[key] {
 		for {
@@ -220,6 +219,7 @@ loop:
 					}
 				}
 			}
+
 			specs = append(specs, spec)
 			s = skipSpace(s)
 			if !strings.HasPrefix(s, ",") {
@@ -228,7 +228,8 @@ loop:
 			s = skipSpace(s[1:])
 		}
 	}
-	return
+
+	return specs
 }
 
 func skipSpace(s string) (rest string) {
@@ -308,7 +309,7 @@ func expectTokenOrQuoted(s string) (value string, rest string) {
 			p := make([]byte, len(s)-1)
 			j := copy(p, s[:i])
 			escape := true
-			for i = i + 1; i < len(s); i++ { //nolint:gocritic
+			for i++; i < len(s); i++ {
 				b := s[i]
 				switch {
 				case escape:
diff --git a/middleware/parameter.go b/middleware/parameter.go
index 97acfc1..9c3353a 100644
--- a/middleware/parameter.go
+++ b/middleware/parameter.go
@@ -12,7 +12,6 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-//nolint:goconst
 package middleware
 
 import (
@@ -35,6 +34,11 @@ import (
 
 const defaultMaxMemory = 32 << 20
 
+const (
+	typeString = "string"
+	typeArray  = "array"
+)
+
 var textUnmarshalType = reflect.TypeOf(new(encoding.TextUnmarshaler)).Elem()
 
 func newUntypedParamBinder(param spec.Parameter, spec *spec.Swagger, formats strfmt.Registry) *untypedParamBinder {
@@ -67,7 +71,7 @@ func (p *untypedParamBinder) typeForSchema(tpe, format string, items *spec.Items
 	case "boolean":
 		return reflect.TypeOf(true)
 
-	case "string":
+	case typeString:
 		if tt, ok := p.formats.GetType(format); ok {
 			return tt
 		}
@@ -95,7 +99,7 @@ func (p *untypedParamBinder) typeForSchema(tpe, format string, items *spec.Items
 			return reflect.TypeOf(float64(0))
 		}
 
-	case "array":
+	case typeArray:
 		if items == nil {
 			return nil
 		}
@@ -120,7 +124,7 @@ func (p *untypedParamBinder) allowsMulti() bool {
 
 func (p *untypedParamBinder) readValue(values runtime.Gettable, target reflect.Value) ([]string, bool, bool, error) {
 	name, in, cf, tpe := p.parameter.Name, p.parameter.In, p.parameter.CollectionFormat, p.parameter.Type
-	if tpe == "array" {
+	if tpe == typeArray {
 		if cf == "multi" {
 			if !p.allowsMulti() {
 				return nil, false, false, errors.InvalidCollectionFormat(name, in, cf)
@@ -209,10 +213,11 @@ func (p *untypedParamBinder) Bind(request *http.Request, routeParams RouteParams
 			if ffErr != nil {
 				if p.parameter.Required {
 					return errors.NewParseError(p.Name, p.parameter.In, "", ffErr)
-				} else { //nolint:revive
-					return nil
 				}
+
+				return nil
 			}
+
 			target.Set(reflect.ValueOf(runtime.File{Data: file, Header: header}))
 			return nil
 		}
@@ -264,7 +269,7 @@ func (p *untypedParamBinder) Bind(request *http.Request, routeParams RouteParams
 }
 
 func (p *untypedParamBinder) bindValue(data []string, hasKey bool, target reflect.Value) error {
-	if p.parameter.Type == "array" {
+	if p.parameter.Type == typeArray {
 		return p.setSliceFieldValue(target, p.parameter.Default, data, hasKey)
 	}
 	var d string
@@ -318,7 +323,7 @@ func (p *untypedParamBinder) setFieldValue(target reflect.Value, defaultValue in
 		return nil
 	}
 
-	switch target.Kind() { //nolint:exhaustive
+	switch target.Kind() { //nolint:exhaustive // we want to check only types that map from a swagger parameter
 	case reflect.Bool:
 		if data == "" {
 			if target.CanSet() {
diff --git a/middleware/rapidoc.go b/middleware/rapidoc.go
index c059399..5cb5314 100644
--- a/middleware/rapidoc.go
+++ b/middleware/rapidoc.go
@@ -1,4 +1,4 @@
-//nolint:dupl,goconst
+//nolint:dupl
 package middleware
 
 import (
@@ -29,16 +29,16 @@ func (r *RapiDocOpts) EnsureDefaults() {
 		r.BasePath = "/"
 	}
 	if r.Path == "" {
-		r.Path = "docs"
+		r.Path = defaultDocsPath
 	}
 	if r.SpecURL == "" {
-		r.SpecURL = "/swagger.json"
+		r.SpecURL = defaultDocsURL
 	}
 	if r.RapiDocURL == "" {
 		r.RapiDocURL = rapidocLatest
 	}
 	if r.Title == "" {
-		r.Title = "API documentation"
+		r.Title = defaultDocsTitle
 	}
 }
 
diff --git a/middleware/redoc.go b/middleware/redoc.go
index 665d059..ca1d4ed 100644
--- a/middleware/redoc.go
+++ b/middleware/redoc.go
@@ -29,16 +29,16 @@ func (r *RedocOpts) EnsureDefaults() {
 		r.BasePath = "/"
 	}
 	if r.Path == "" {
-		r.Path = "docs"
+		r.Path = defaultDocsPath
 	}
 	if r.SpecURL == "" {
-		r.SpecURL = "/swagger.json"
+		r.SpecURL = defaultDocsURL
 	}
 	if r.RedocURL == "" {
 		r.RedocURL = redocLatest
 	}
 	if r.Title == "" {
-		r.Title = "API documentation"
+		r.Title = defaultDocsTitle
 	}
 }
 
diff --git a/middleware/request.go b/middleware/request.go
index 760c378..d4b9fc6 100644
--- a/middleware/request.go
+++ b/middleware/request.go
@@ -65,7 +65,7 @@ func (o *UntypedRequestBinder) Bind(request *http.Request, routeParams RoutePara
 		if isMap {
 			tpe := binder.Type()
 			if tpe == nil {
-				if param.Schema.Type.Contains("array") {
+				if param.Schema.Type.Contains(typeArray) {
 					tpe = reflect.TypeOf([]interface{}{})
 				} else {
 					tpe = reflect.TypeOf(map[string]interface{}{})
diff --git a/middleware/router.go b/middleware/router.go
index 5e057b8..46b8f87 100644
--- a/middleware/router.go
+++ b/middleware/router.go
@@ -449,11 +449,11 @@ func (d *defaultRouteBuilder) AddRoute(method, path string, operation *spec.Oper
 
 func (d *defaultRouteBuilder) buildAuthenticators(operation *spec.Operation) RouteAuthenticators {
 	requirements := d.analyzer.SecurityRequirementsFor(operation)
-	var auths []RouteAuthenticator //nolint:prealloc
+	auths := make([]RouteAuthenticator, 0, len(requirements))
 	for _, reqs := range requirements {
-		var schemes []string
+		schemes := make([]string, 0, len(reqs))
 		scopes := make(map[string][]string, len(reqs))
-		var scopeSlices [][]string
+		scopeSlices := make([][]string, 0, len(reqs))
 		for _, req := range reqs {
 			schemes = append(schemes, req.Name)
 			scopes[req.Name] = req.Scopes
diff --git a/middleware/swaggerui.go b/middleware/swaggerui.go
index b4dea29..846e3cf 100644
--- a/middleware/swaggerui.go
+++ b/middleware/swaggerui.go
@@ -37,10 +37,10 @@ func (r *SwaggerUIOpts) EnsureDefaults() {
 		r.BasePath = "/"
 	}
 	if r.Path == "" {
-		r.Path = "docs"
+		r.Path = defaultDocsPath
 	}
 	if r.SpecURL == "" {
-		r.SpecURL = "/swagger.json"
+		r.SpecURL = defaultDocsURL
 	}
 	if r.OAuthCallbackURL == "" {
 		r.OAuthCallbackURL = path.Join(r.BasePath, r.Path, "oauth2-callback")
@@ -61,7 +61,7 @@ func (r *SwaggerUIOpts) EnsureDefaults() {
 		r.Favicon32 = swaggerFavicon32Latest
 	}
 	if r.Title == "" {
-		r.Title = "API documentation"
+		r.Title = defaultDocsTitle
 	}
 }
 
diff --git a/middleware/ui_defaults.go b/middleware/ui_defaults.go
new file mode 100644
index 0000000..25817d2
--- /dev/null
+++ b/middleware/ui_defaults.go
@@ -0,0 +1,8 @@
+package middleware
+
+const (
+	// constants that are common to all UI-serving middlewares
+	defaultDocsPath  = "docs"
+	defaultDocsURL   = "/swagger.json"
+	defaultDocsTitle = "API Documentation"
+)
diff --git a/middleware/untyped/api.go b/middleware/untyped/api.go
index 94788d2..7b7269b 100644
--- a/middleware/untyped/api.go
+++ b/middleware/untyped/api.go
@@ -197,30 +197,31 @@ func (d *API) Validate() error {
 
 // validateWith validates the registrations in this API against the provided spec analyzer
 func (d *API) validate() error {
-	var consumes []string //nolint:prealloc
+	consumes := make([]string, 0, len(d.consumers))
 	for k := range d.consumers {
 		consumes = append(consumes, k)
 	}
 
-	var produces []string //nolint:prealloc
+	produces := make([]string, 0, len(d.producers))
 	for k := range d.producers {
 		produces = append(produces, k)
 	}
 
-	var authenticators []string //nolint:prealloc
+	authenticators := make([]string, 0, len(d.authenticators))
 	for k := range d.authenticators {
 		authenticators = append(authenticators, k)
 	}
 
-	var operations []string
+	operations := make([]string, 0, len(d.operations))
 	for m, v := range d.operations {
 		for p := range v {
 			operations = append(operations, fmt.Sprintf("%s %s", strings.ToUpper(m), p))
 		}
 	}
 
-	var definedAuths []string //nolint:prealloc
-	for k := range d.spec.Spec().SecurityDefinitions {
+	secDefinitions := d.spec.Spec().SecurityDefinitions
+	definedAuths := make([]string, 0, len(secDefinitions))
+	for k := range secDefinitions {
 		definedAuths = append(definedAuths, k)
 	}
 
@@ -267,7 +268,7 @@ func (d *API) verify(name string, registrations []string, expectations []string)
 		delete(expected, k)
 	}
 
-	var unregistered []string //nolint:prealloc
+	unregistered := make([]string, 0, len(expected))
 	for k := range expected {
 		unregistered = append(unregistered, k)
 	}
diff --git a/request.go b/request.go
index 3b9e983..9e3e1ec 100644
--- a/request.go
+++ b/request.go
@@ -16,6 +16,7 @@ package runtime
 
 import (
 	"bufio"
+	"context"
 	"errors"
 	"io"
 	"net/http"
@@ -114,9 +115,11 @@ func (p *peekingReader) Close() error {
 	return nil
 }
 
-// JSONRequest creates a new http request with json headers set
+// JSONRequest creates a new http request with json headers set.
+//
+// It uses context.Background.
 func JSONRequest(method, urlStr string, body io.Reader) (*http.Request, error) {
-	req, err := http.NewRequest(method, urlStr, body) //nolint:noctx
+	req, err := http.NewRequestWithContext(context.Background(), method, urlStr, body)
 	if err != nil {
 		return nil, err
 	}
diff --git a/security/authenticator.go b/security/authenticator.go
index 8653b86..bb30472 100644
--- a/security/authenticator.go
+++ b/security/authenticator.go
@@ -25,8 +25,9 @@ import (
 )
 
 const (
-	query  = "query"
-	header = "header"
+	query            = "query"
+	header           = "header"
+	accessTokenParam = "access_token"
 )
 
 // HttpAuthenticator is a function that authenticates a HTTP request
@@ -158,7 +159,7 @@ func APIKeyAuth(name, in string, authenticate TokenAuthentication) runtime.Authe
 	inl := strings.ToLower(in)
 	if inl != query && inl != header {
 		// panic because this is most likely a typo
-		panic(errors.New(500, "api key auth: in value needs to be either \"query\" or \"header\".")) //nolint:revive
+		panic(errors.New(500, "api key auth: in value needs to be either \"query\" or \"header\""))
 	}
 
 	var getToken func(*http.Request) string
@@ -186,7 +187,7 @@ func APIKeyAuthCtx(name, in string, authenticate TokenAuthenticationCtx) runtime
 	inl := strings.ToLower(in)
 	if inl != query && inl != header {
 		// panic because this is most likely a typo
-		panic(errors.New(500, "api key auth: in value needs to be either \"query\" or \"header\".")) //nolint:revive
+		panic(errors.New(500, "api key auth: in value needs to be either \"query\" or \"header\""))
 	}
 
 	var getToken func(*http.Request) string
@@ -226,12 +227,12 @@ func BearerAuth(name string, authenticate ScopedTokenAuthentication) runtime.Aut
 		}
 		if token == "" {
 			qs := r.Request.URL.Query()
-			token = qs.Get("access_token")
+			token = qs.Get(accessTokenParam)
 		}
 		//#nosec
 		ct, _, _ := runtime.ContentType(r.Request.Header)
 		if token == "" && (ct == "application/x-www-form-urlencoded" || ct == "multipart/form-data") {
-			token = r.Request.FormValue("access_token")
+			token = r.Request.FormValue(accessTokenParam)
 		}
 
 		if token == "" {
@@ -256,12 +257,12 @@ func BearerAuthCtx(name string, authenticate ScopedTokenAuthenticationCtx) runti
 		}
 		if token == "" {
 			qs := r.Request.URL.Query()
-			token = qs.Get("access_token")
+			token = qs.Get(accessTokenParam)
 		}
 		//#nosec
 		ct, _, _ := runtime.ContentType(r.Request.Header)
 		if token == "" && (ct == "application/x-www-form-urlencoded" || ct == "multipart/form-data") {
-			token = r.Request.FormValue("access_token")
+			token = r.Request.FormValue(accessTokenParam)
 		}
 
 		if token == "" {


Test patch:
diff --git a/bytestream.go b/bytestream.go
index 3142a09..0a6b8ec 100644
--- a/bytestream.go
+++ b/bytestream.go
@@ -52,14 +52,15 @@ func ByteStreamConsumer(opts ...byteStreamOpt) Consumer {
 			return errors.New("ByteStreamConsumer requires a reader") // early exit
 		}
 
-		close := defaultCloser //nolint:revive,predeclared
+		closer := defaultCloser
 		if vals.Close {
 			if cl, ok := reader.(io.Closer); ok {
-				close = cl.Close //nolint:revive
+				closer = cl.Close
 			}
 		}
-		//nolint:errcheck // closing a reader wouldn't fail.
-		defer close()
+		defer func() {
+			_ = closer()
+		}()
 
 		if wrtr, ok := data.(io.Writer); ok {
 			_, err := io.Copy(wrtr, reader)
@@ -109,14 +110,15 @@ func ByteStreamProducer(opts ...byteStreamOpt) Producer {
 		if writer == nil {
 			return errors.New("ByteStreamProducer requires a writer") // early exit
 		}
-		close := defaultCloser //nolint:revive,predeclared
+		closer := defaultCloser
 		if vals.Close {
 			if cl, ok := writer.(io.Closer); ok {
-				close = cl.Close //nolint:revive
+				closer = cl.Close
 			}
 		}
-		//nolint:errcheck // TODO: closing a writer would fail.
-		defer close()
+		defer func() {
+			_ = closer()
+		}()
 
 		if rc, ok := data.(io.ReadCloser); ok {
 			defer rc.Close()
diff --git a/client/opentelemetry_test.go b/client/opentelemetry_test.go
index 3a844cb..a5f41e0 100644
--- a/client/opentelemetry_test.go
+++ b/client/opentelemetry_test.go
@@ -121,7 +121,7 @@ func assertOpenTelemetrySubmit(t *testing.T, operation *runtime.ClientOperation,
 		attribute.String("http.route", "/kubernetes-clusters/{cluster_id}"),
 		attribute.String("http.method", http.MethodGet),
 		attribute.String("span.kind", trace.SpanKindClient.String()),
-		attribute.String("http.scheme", "https"),
+		attribute.String("http.scheme", schemeHTTPS),
 		// NOTE: this becomes http.response.status_code with semconv v1.21
 		attribute.Int("http.status_code", 490),
 	}, span.Attributes)
diff --git a/client/opentracing_test.go b/client/opentracing_test.go
index 9bb5cab..cd33f9d 100644
--- a/client/opentracing_test.go
+++ b/client/opentracing_test.go
@@ -42,7 +42,7 @@ type mockRuntime struct {
 func (m *mockRuntime) Submit(operation *runtime.ClientOperation) (interface{}, error) {
 	_ = operation.Params.WriteToRequest(&m.req, nil)
 	_, _ = operation.Reader.ReadResponse(&tres{}, nil)
-	return nil, nil //nolint:nilnil
+	return map[string]interface{}{}, nil
 }
 
 func testOperation(ctx context.Context) *runtime.ClientOperation {
@@ -52,7 +52,7 @@ func testOperation(ctx context.Context) *runtime.ClientOperation {
 		PathPattern:        "/kubernetes-clusters/{cluster_id}",
 		ProducesMediaTypes: []string{"application/json"},
 		ConsumesMediaTypes: []string{"application/json"},
-		Schemes:            []string{"https"},
+		Schemes:            []string{schemeHTTPS},
 		Reader: runtime.ClientResponseReaderFunc(func(runtime.ClientResponse, runtime.Consumer) (interface{}, error) {
 			return nil, nil
 		}),
diff --git a/client/request_test.go b/client/request_test.go
index a8ab7d2..4061694 100644
--- a/client/request_test.go
+++ b/client/request_test.go
@@ -769,7 +769,7 @@ func TestGetBodyCallsBeforeRoundTrip(t *testing.T) {
 		}),
 	}
 
-	openAPIClient := New(hu.Host, "/", []string{"http"})
+	openAPIClient := New(hu.Host, "/", []string{schemeHTTP})
 	res, err := openAPIClient.Submit(operation)
 	require.NoError(t, err)
 
diff --git a/client/runtime_test.go b/client/runtime_test.go
index 58fc2ff..b3a5ce4 100644
--- a/client/runtime_test.go
+++ b/client/runtime_test.go
@@ -299,7 +299,7 @@ func TestRuntime_ManualCertificateValidation(t *testing.T) {
 	require.NoError(t, err)
 	hu, err := url.Parse(server.URL)
 	require.NoError(t, err)
-	rt := NewWithClient(hu.Host, "/", []string{"https"}, client)
+	rt := NewWithClient(hu.Host, "/", []string{schemeHTTPS}, client)
 
 	rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error {
 		return nil
@@ -351,7 +351,7 @@ func TestRuntime_Concurrent(t *testing.T) {
 	hu, err := url.Parse(server.URL)
 	require.NoError(t, err)
 
-	rt := New(hu.Host, "/", []string{"http"})
+	rt := New(hu.Host, "/", []string{schemeHTTP})
 	resCC := make(chan interface{})
 	errCC := make(chan error)
 	var res interface{}
@@ -426,7 +426,7 @@ func TestRuntime_Canary(t *testing.T) {
 
 	hu, err := url.Parse(server.URL)
 	require.NoError(t, err)
-	rt := New(hu.Host, "/", []string{"http"})
+	rt := New(hu.Host, "/", []string{schemeHTTP})
 	res, err := rt.Submit(&runtime.ClientOperation{
 		ID:          "getTasks",
 		Method:      http.MethodGet,
@@ -478,7 +478,7 @@ func TestRuntime_XMLCanary(t *testing.T) {
 	hu, err := url.Parse(server.URL)
 	require.NoError(t, err)
 
-	rt := New(hu.Host, "/", []string{"http"})
+	rt := New(hu.Host, "/", []string{schemeHTTP})
 	res, err := rt.Submit(&runtime.ClientOperation{
 		ID:          "getTasks",
 		Method:      http.MethodGet,
@@ -520,7 +520,7 @@ func TestRuntime_TextCanary(t *testing.T) {
 	hu, err := url.Parse(server.URL)
 	require.NoError(t, err)
 
-	rt := New(hu.Host, "/", []string{"http"})
+	rt := New(hu.Host, "/", []string{schemeHTTP})
 	res, err := rt.Submit(&runtime.ClientOperation{
 		ID:          "getTasks",
 		Method:      http.MethodGet,
@@ -565,7 +565,7 @@ func TestRuntime_CSVCanary(t *testing.T) {
 	hu, err := url.Parse(server.URL)
 	require.NoError(t, err)
 
-	rt := New(hu.Host, "/", []string{"http"})
+	rt := New(hu.Host, "/", []string{schemeHTTP})
 	res, err := rt.Submit(&runtime.ClientOperation{
 		ID:          "getTasks",
 		Method:      http.MethodGet,
@@ -604,9 +604,9 @@ func TestRuntime_CustomTransport(t *testing.T) {
 		{false, "task 2 content", 2},
 	}
 
-	rt := New("localhost:3245", "/", []string{"ws", "wss", "https"})
+	rt := New("localhost:3245", "/", []string{"ws", "wss", schemeHTTPS})
 	rt.Transport = roundTripperFunc(func(req *http.Request) (*http.Response, error) {
-		if req.URL.Scheme != "https" {
+		if req.URL.Scheme != schemeHTTPS {
 			return nil, errors.New("this was not a https request")
 		}
 		assert.Equal(t, "localhost:3245", req.Host)
@@ -627,7 +627,7 @@ func TestRuntime_CustomTransport(t *testing.T) {
 		ID:          "getTasks",
 		Method:      http.MethodGet,
 		PathPattern: "/",
-		Schemes:     []string{"ws", "wss", "https"},
+		Schemes:     []string{"ws", "wss", schemeHTTPS},
 		Params:      rwrtr,
 		Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
 			if response.Code() == http.StatusOK {
@@ -680,7 +680,7 @@ func TestRuntime_CustomCookieJar(t *testing.T) {
 	hu, err := url.Parse(server.URL)
 	require.NoError(t, err)
 
-	rt := New(hu.Host, "/", []string{"http"})
+	rt := New(hu.Host, "/", []string{schemeHTTP})
 	rt.Jar, err = cookiejar.New(nil)
 	require.NoError(t, err)
 
@@ -693,7 +693,7 @@ func TestRuntime_CustomCookieJar(t *testing.T) {
 			AuthInfo:    authInfo,
 			Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, _ runtime.Consumer) (interface{}, error) {
 				if response.Code() == http.StatusOK {
-					return nil, nil //nolint:nilnil
+					return map[string]interface{}{}, nil
 				}
 				return nil, errors.New("generic error")
 			}),
@@ -735,7 +735,7 @@ func TestRuntime_AuthCanary(t *testing.T) {
 	hu, err := url.Parse(server.URL)
 	require.NoError(t, err)
 
-	rt := New(hu.Host, "/", []string{"http"})
+	rt := New(hu.Host, "/", []string{schemeHTTP})
 	res, err := rt.Submit(&runtime.ClientOperation{
 		ID:     "getTasks",
 		Params: rwrtr,
@@ -783,12 +783,12 @@ func TestRuntime_PickConsumer(t *testing.T) {
 	hu, err := url.Parse(server.URL)
 	require.NoError(t, err)
 
-	rt := New(hu.Host, "/", []string{"http"})
+	rt := New(hu.Host, "/", []string{schemeHTTP})
 	res, err := rt.Submit(&runtime.ClientOperation{
 		ID:                 "getTasks",
 		Method:             "POST",
 		PathPattern:        "/",
-		Schemes:            []string{"http"},
+		Schemes:            []string{schemeHTTP},
 		ConsumesMediaTypes: []string{"application/octet-stream"},
 		Params:             rwrtr,
 		Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
@@ -837,12 +837,12 @@ func TestRuntime_ContentTypeCanary(t *testing.T) {
 	hu, err := url.Parse(server.URL)
 	require.NoError(t, err)
 
-	rt := New(hu.Host, "/", []string{"http"})
+	rt := New(hu.Host, "/", []string{schemeHTTP})
 	res, err := rt.Submit(&runtime.ClientOperation{
 		ID:          "getTasks",
 		Method:      http.MethodGet,
 		PathPattern: "/",
-		Schemes:     []string{"http"},
+		Schemes:     []string{schemeHTTP},
 		Params:      rwrtr,
 		Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
 			if response.Code() == http.StatusOK {
@@ -892,12 +892,12 @@ func TestRuntime_ChunkedResponse(t *testing.T) {
 	hu, err := url.Parse(server.URL)
 	require.NoError(t, err)
 
-	rt := New(hu.Host, "/", []string{"http"})
+	rt := New(hu.Host, "/", []string{schemeHTTP})
 	res, err := rt.Submit(&runtime.ClientOperation{
 		ID:          "getTasks",
 		Method:      http.MethodGet,
 		PathPattern: "/",
-		Schemes:     []string{"http"},
+		Schemes:     []string{schemeHTTP},
 		Params:      rwrtr,
 		Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
 			if response.Code() == http.StatusOK {
@@ -922,7 +922,7 @@ func TestRuntime_DebugValue(t *testing.T) {
 	t.Run("empty DEBUG means Debug is False", func(t *testing.T) {
 		t.Setenv("DEBUG", "")
 
-		runtime := New("", "/", []string{"https"})
+		runtime := New("", "/", []string{schemeHTTPS})
 		assert.False(t, runtime.Debug)
 	})
 
@@ -930,42 +930,42 @@ func TestRuntime_DebugValue(t *testing.T) {
 		t.Run("with numerical value", func(t *testing.T) {
 			t.Setenv("DEBUG", "1")
 
-			runtime := New("", "/", []string{"https"})
+			runtime := New("", "/", []string{schemeHTTPS})
 			assert.True(t, runtime.Debug)
 		})
 
 		t.Run("with boolean value true", func(t *testing.T) {
 			t.Setenv("DEBUG", "true")
 
-			runtime := New("", "/", []string{"https"})
+			runtime := New("", "/", []string{schemeHTTPS})
 			assert.True(t, runtime.Debug)
 		})
 
 		t.Run("with boolean value false", func(t *testing.T) {
 			t.Setenv("DEBUG", "false")
 
-			runtime := New("", "/", []string{"https"})
+			runtime := New("", "/", []string{schemeHTTPS})
 			assert.False(t, runtime.Debug)
 		})
 
 		t.Run("with string value ", func(t *testing.T) {
 			t.Setenv("DEBUG", "foo")
 
-			runtime := New("", "/", []string{"https"})
+			runtime := New("", "/", []string{schemeHTTPS})
 			assert.True(t, runtime.Debug)
 		})
 	})
 }
 
 func TestRuntime_OverrideScheme(t *testing.T) {
-	runtime := New("", "/", []string{"https"})
-	sch := runtime.pickScheme([]string{"http"})
-	assert.Equal(t, "https", sch)
+	runtime := New("", "/", []string{schemeHTTPS})
+	sch := runtime.pickScheme([]string{schemeHTTP})
+	assert.Equal(t, schemeHTTPS, sch)
 }
 
 func TestRuntime_OverrideClient(t *testing.T) {
 	client := &http.Client{}
-	runtime := NewWithClient("", "/", []string{"https"}, client)
+	runtime := NewWithClient("", "/", []string{schemeHTTPS}, client)
 	var i int
 	runtime.clientOnce.Do(func() { i++ })
 	assert.Equal(t, client, runtime.client)
@@ -986,7 +986,7 @@ func (o *overrideRoundTripper) RoundTrip(_ *http.Request) (*http.Response, error
 
 func TestRuntime_OverrideClientOperation(t *testing.T) {
 	client := &http.Client{}
-	rt := NewWithClient("", "/", []string{"https"}, client)
+	rt := NewWithClient("", "/", []string{schemeHTTPS}, client)
 	var i int
 	rt.clientOnce.Do(func() { i++ })
 	assert.Equal(t, client, rt.client)
@@ -1003,7 +1003,7 @@ func TestRuntime_OverrideClientOperation(t *testing.T) {
 			return nil
 		}),
 		Reader: runtime.ClientResponseReaderFunc(func(_ runtime.ClientResponse, _ runtime.Consumer) (interface{}, error) {
-			return nil, nil //nolint:nilnil
+			return map[string]interface{}{}, nil
 		}),
 	})
 	require.NoError(t, err)
@@ -1029,7 +1029,7 @@ func TestRuntime_PreserveTrailingSlash(t *testing.T) {
 	hu, err := url.Parse(server.URL)
 	require.NoError(t, err)
 
-	rt := New(hu.Host, "/", []string{"http"})
+	rt := New(hu.Host, "/", []string{schemeHTTP})
 	rwrtr := runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, _ strfmt.Registry) error {
 		return nil
 	})
@@ -1044,7 +1044,7 @@ func TestRuntime_PreserveTrailingSlash(t *testing.T) {
 				return nil, errors.New("expected Submit to preserve trailing slashes - this caused a redirect")
 			}
 			if response.Code() == http.StatusOK {
-				return nil, nil //nolint:nilnil
+				return map[string]interface{}{}, nil
 			}
 			return nil, errors.New("generic error")
 		}),
@@ -1067,14 +1067,14 @@ func TestRuntime_FallbackConsumer(t *testing.T) {
 
 	hu, err := url.Parse(server.URL)
 	require.NoError(t, err)
-	rt := New(hu.Host, "/", []string{"http"})
+	rt := New(hu.Host, "/", []string{schemeHTTP})
 
 	// without the fallback consumer
 	_, err = rt.Submit(&runtime.ClientOperation{
 		ID:                 "getTasks",
 		Method:             "POST",
 		PathPattern:        "/",
-		Schemes:            []string{"http"},
+		Schemes:            []string{schemeHTTP},
 		ConsumesMediaTypes: []string{"application/octet-stream"},
 		Params:             rwrtr,
 		Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
@@ -1097,7 +1097,7 @@ func TestRuntime_FallbackConsumer(t *testing.T) {
 		ID:                 "getTasks",
 		Method:             "POST",
 		PathPattern:        "/",
-		Schemes:            []string{"http"},
+		Schemes:            []string{schemeHTTP},
 		ConsumesMediaTypes: []string{"application/octet-stream"},
 		Params:             rwrtr,
 		Reader: runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
@@ -1145,7 +1145,7 @@ func TestRuntime_AuthHeaderParamDetected(t *testing.T) {
 	hu, err := url.Parse(server.URL)
 	require.NoError(t, err)
 
-	rt := New(hu.Host, "/", []string{"http"})
+	rt := New(hu.Host, "/", []string{schemeHTTP})
 	rt.DefaultAuthentication = BearerToken("not-the-super-secret-token")
 	res, err := rt.Submit(&runtime.ClientOperation{
 		ID:     "getTasks",
diff --git a/internal/testing/petstore/api.go b/internal/testing/petstore/api.go
index 9765ad6..b9276b9 100644
--- a/internal/testing/petstore/api.go
+++ b/internal/testing/petstore/api.go
@@ -169,5 +169,5 @@ func (s *stubOperationHandler) ParameterModel() interface{} {
 }
 
 func (s *stubOperationHandler) Handle(_ interface{}) (interface{}, error) {
-	return nil, nil //nolint:nilnil
+	return map[string]interface{}{}, nil
 }
diff --git a/internal/testing/simplepetstore/api.go b/internal/testing/simplepetstore/api.go
index df7f1dd..044710e 100644
--- a/internal/testing/simplepetstore/api.go
+++ b/internal/testing/simplepetstore/api.go
@@ -59,7 +59,7 @@ var createPet = runtime.OperationHandlerFunc(func(data interface{}) (interface{}
 var deletePet = runtime.OperationHandlerFunc(func(data interface{}) (interface{}, error) {
 	id := data.(map[string]interface{})["id"].(int64)
 	removePet(id)
-	return nil, nil //nolint:nilnil
+	return map[string]interface{}{}, nil
 })
 
 var getPetByID = runtime.OperationHandlerFunc(func(data interface{}) (interface{}, error) {
diff --git a/middleware/context_test.go b/middleware/context_test.go
index 0db0042..4c0a62d 100644
--- a/middleware/context_test.go
+++ b/middleware/context_test.go
@@ -49,7 +49,7 @@ func (s *stubOperationHandler) ParameterModel() interface{} {
 }
 
 func (s *stubOperationHandler) Handle(_ interface{}) (interface{}, error) {
-	return nil, nil //nolint:nilnil
+	return map[string]interface{}{}, nil
 }
 
 func init() {
diff --git a/middleware/denco/server_test.go b/middleware/denco/server_test.go
index e887c15..fcc56db 100644
--- a/middleware/denco/server_test.go
+++ b/middleware/denco/server_test.go
@@ -84,7 +84,9 @@ func TestNotFound(t *testing.T) {
 		w.WriteHeader(http.StatusServiceUnavailable)
 		fmt.Fprintf(w, "method: %s, path: %s, params: %v", r.Method, r.URL.Path, params)
 	}
-	res, err := http.Get(server.URL) //nolint:noctx
+	req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, server.URL, nil)
+	require.NoError(t, err)
+	res, err := http.DefaultClient.Do(req)
 	require.NoError(t, err)
 
 	defer res.Body.Close()
diff --git a/middleware/parameter_test.go b/middleware/parameter_test.go
index c2b0ddd..cbec8ab 100644
--- a/middleware/parameter_test.go
+++ b/middleware/parameter_test.go
@@ -46,15 +46,14 @@ func np(param *spec.Parameter) *untypedParamBinder {
 var stringItems = new(spec.Items)
 
 func init() {
-	stringItems.Type = "string"
+	stringItems.Type = typeString
 }
 
 func testCollectionFormat(t *testing.T, param *spec.Parameter, valid bool) {
 	binder := &untypedParamBinder{
 		parameter: param,
 	}
-	// ICI
-	_, _, _, err := binder.readValue(runtime.Values(nil), reflect.ValueOf(nil)) //nolint:dogsled
+	_, _, _, err := binder.readValue(runtime.Values(nil), reflect.ValueOf(nil)) //nolint:dogsled // we just want to test the error
 	if valid {
 		require.NoError(t, err)
 	} else {
@@ -109,7 +108,7 @@ func validateRequiredAllowEmptyTest(t *testing.T, param *spec.Parameter, value r
 }
 
 func TestRequiredValidation(t *testing.T) {
-	strParam := spec.QueryParam("name").Typed("string", "").AsRequired()
+	strParam := spec.QueryParam("name").Typed(typeString, "").AsRequired()
 	validateRequiredTest(t, strParam, reflect.ValueOf(""))
 	validateRequiredAllowEmptyTest(t, strParam, reflect.ValueOf(""))
 
@@ -127,11 +126,11 @@ func TestRequiredValidation(t *testing.T) {
 	validateRequiredTest(t, doubleParam, reflect.ValueOf(float64(0)))
 	validateRequiredAllowEmptyTest(t, doubleParam, reflect.ValueOf(float64(0)))
 
-	dateTimeParam := spec.QueryParam("registered").Typed("string", "date-time").AsRequired()
+	dateTimeParam := spec.QueryParam("registered").Typed(typeString, "date-time").AsRequired()
 	validateRequiredTest(t, dateTimeParam, reflect.ValueOf(strfmt.DateTime{}))
 	// validateRequiredAllowEmptyTest(t, dateTimeParam, reflect.ValueOf(strfmt.DateTime{}))
 
-	dateParam := spec.QueryParam("registered").Typed("string", "date").AsRequired()
+	dateParam := spec.QueryParam("registered").Typed(typeString, "date").AsRequired()
 	validateRequiredTest(t, dateParam, reflect.ValueOf(strfmt.Date{}))
 	// validateRequiredAllowEmptyTest(t, dateParam, reflect.ValueOf(strfmt.DateTime{}))
 
@@ -234,7 +233,7 @@ func TestTypeValidation(t *testing.T) {
 		require.EqualError(t, err, invalidTypeError(doubleParam, str4).Error())
 
 		// fails for invalid string
-		dateParam := newParam("badDate").Typed("string", "date")
+		dateParam := newParam("badDate").Typed(typeString, "date")
 		value = reflect.ValueOf(strfmt.Date{})
 		binder = np(dateParam)
 		err = binder.bindValue([]string{"yada"}, true, value)
@@ -242,7 +241,7 @@ func TestTypeValidation(t *testing.T) {
 		require.EqualError(t, err, invalidTypeError(dateParam, "yada").Error())
 
 		// fails for invalid string
-		dateTimeParam := newParam("badDateTime").Typed("string", "date-time")
+		dateTimeParam := newParam("badDateTime").Typed(typeString, "date-time")
 		value = reflect.ValueOf(strfmt.DateTime{})
 		binder = np(dateTimeParam)
 		err = binder.bindValue([]string{"yada"}, true, value)
@@ -250,7 +249,7 @@ func TestTypeValidation(t *testing.T) {
 		require.EqualError(t, err, invalidTypeError(dateTimeParam, "yada").Error())
 
 		// fails for invalid string
-		byteParam := newParam("badByte").Typed("string", "byte")
+		byteParam := newParam("badByte").Typed(typeString, "byte")
 		values := url.Values(map[string][]string{})
 		values.Add("badByte", "yaüda")
 		v5 := []byte{}
@@ -271,7 +270,7 @@ func TestTypeDetectionInvalidItems(t *testing.T) {
 	assert.Nil(t, binder.Type())
 
 	items := new(spec.Items)
-	items.Type = "array"
+	items.Type = typeArray
 	withInvalidItems := spec.QueryParam("invalidItems").CollectionOf(items, "")
 	binder = &untypedParamBinder{
 		Name:      "invalidItems",
@@ -331,7 +330,7 @@ func TestTypeDetectionInvalidItems(t *testing.T) {
 // 	}
 //
 // 	params := parametersForAllTypes("")
-// 	emailParam := spec.QueryParam("email").Typed("string", "email")
+// 	emailParam := spec.QueryParam("email").Typed(typeString, "email")
 // 	params["email"] = *emailParam
 //
 // 	fileParam := spec.FileParam("file")
diff --git a/middleware/rapidoc_test.go b/middleware/rapidoc_test.go
index c15550a..8c9f0ce 100644
--- a/middleware/rapidoc_test.go
+++ b/middleware/rapidoc_test.go
@@ -2,6 +2,7 @@ package middleware
 
 import (
 	"context"
+	"fmt"
 	"net/http"
 	"net/http/httptest"
 	"testing"
@@ -19,7 +20,9 @@ func TestRapiDocMiddleware(t *testing.T) {
 	rapidoc.ServeHTTP(recorder, req)
 	assert.Equal(t, http.StatusOK, recorder.Code)
 	assert.Equal(t, "text/html; charset=utf-8", recorder.Header().Get("Content-Type"))
-	assert.Contains(t, recorder.Body.String(), "<title>API documentation</title>")
-	assert.Contains(t, recorder.Body.String(), "<rapi-doc spec-url=\"/swagger.json\"></rapi-doc>")
+	var o RapiDocOpts
+	o.EnsureDefaults()
+	assert.Contains(t, recorder.Body.String(), fmt.Sprintf("<title>%s</title>", o.Title))
+	assert.Contains(t, recorder.Body.String(), fmt.Sprintf("<rapi-doc spec-url=%q></rapi-doc>", o.SpecURL))
 	assert.Contains(t, recorder.Body.String(), rapidocLatest)
 }
diff --git a/middleware/redoc_test.go b/middleware/redoc_test.go
index 364d8cf..71a7c1b 100644
--- a/middleware/redoc_test.go
+++ b/middleware/redoc_test.go
@@ -2,6 +2,7 @@ package middleware
 
 import (
 	"context"
+	"fmt"
 	"net/http"
 	"net/http/httptest"
 	"testing"
@@ -19,7 +20,9 @@ func TestRedocMiddleware(t *testing.T) {
 	redoc.ServeHTTP(recorder, req)
 	assert.Equal(t, http.StatusOK, recorder.Code)
 	assert.Equal(t, "text/html; charset=utf-8", recorder.Header().Get("Content-Type"))
-	assert.Contains(t, recorder.Body.String(), "<title>API documentation</title>")
-	assert.Contains(t, recorder.Body.String(), "<redoc spec-url='/swagger.json'></redoc>")
+	var o RedocOpts
+	o.EnsureDefaults()
+	assert.Contains(t, recorder.Body.String(), fmt.Sprintf("<title>%s</title>", o.Title))
+	assert.Contains(t, recorder.Body.String(), fmt.Sprintf("<redoc spec-url='%s'></redoc>", o.SpecURL))
 	assert.Contains(t, recorder.Body.String(), redocLatest)
 }
diff --git a/middleware/request_test.go b/middleware/request_test.go
index 91ba915..b37085e 100644
--- a/middleware/request_test.go
+++ b/middleware/request_test.go
@@ -77,7 +77,7 @@ func parametersForAllTypes(fmt string) map[string]spec.Parameter {
 	if fmt == "" {
 		fmt = csvFormat
 	}
-	nameParam := spec.QueryParam("name").Typed("string", "")
+	nameParam := spec.QueryParam("name").Typed(typeString, "")
 	idParam := spec.PathParam("id").Typed("integer", "int64")
 	ageParam := spec.QueryParam("age").Typed("integer", "int32")
 	scoreParam := spec.QueryParam("score").Typed("number", "float")
@@ -91,13 +91,13 @@ func parametersForAllTypes(fmt string) map[string]spec.Parameter {
 	requestIDParam.Extensions.Add("go-name", "RequestID")
 
 	items := new(spec.Items)
-	items.Type = "string"
+	items.Type = typeString
 	tagsParam := spec.QueryParam("tags").CollectionOf(items, fmt)
 
 	confirmedParam := spec.QueryParam("confirmed").Typed("boolean", "")
-	plannedParam := spec.QueryParam("planned").Typed("string", "date")
-	deliveredParam := spec.QueryParam("delivered").Typed("string", "date-time")
-	pictureParam := spec.QueryParam("picture").Typed("string", "byte") // base64 encoded during transport
+	plannedParam := spec.QueryParam("planned").Typed(typeString, "date")
+	deliveredParam := spec.QueryParam("delivered").Typed(typeString, "date-time")
+	pictureParam := spec.QueryParam("picture").Typed(typeString, "byte") // base64 encoded during transport
 
 	return map[string]spec.Parameter{
 		"ID":        *idParam,
@@ -119,7 +119,7 @@ func parametersForJSONRequestParams(fmt string) map[string]spec.Parameter {
 	if fmt == "" {
 		fmt = csvFormat
 	}
-	nameParam := spec.QueryParam("name").Typed("string", "")
+	nameParam := spec.QueryParam("name").Typed(typeString, "")
 	idParam := spec.PathParam("id").Typed("integer", "int64")
 
 	friendSchema := new(spec.Schema).Typed("object", "")
@@ -130,7 +130,7 @@ func parametersForJSONRequestParams(fmt string) map[string]spec.Parameter {
 	requestIDParam.Extensions.Add("go-name", "RequestID")
 
 	items := new(spec.Items)
-	items.Type = "string"
+	items.Type = typeString
 	tagsParam := spec.QueryParam("tags").CollectionOf(items, fmt)
 
 	return map[string]spec.Parameter{
@@ -145,7 +145,7 @@ func parametersForJSONRequestSliceParams(fmt string) map[string]spec.Parameter {
 	if fmt == "" {
 		fmt = csvFormat
 	}
-	nameParam := spec.QueryParam("name").Typed("string", "")
+	nameParam := spec.QueryParam("name").Typed(typeString, "")
 	idParam := spec.PathParam("id").Typed("integer", "int64")
 
 	friendSchema := new(spec.Schema).Typed("object", "")
@@ -156,7 +156,7 @@ func parametersForJSONRequestSliceParams(fmt string) map[string]spec.Parameter {
 	requestIDParam.Extensions.Add("go-name", "RequestID")
 
 	items := new(spec.Items)
-	items.Type = "string"
+	items.Type = typeString
 	tagsParam := spec.QueryParam("tags").CollectionOf(items, fmt)
 
 	return map[string]spec.Parameter{
@@ -276,7 +276,7 @@ func TestRequestBindingForInvalid(t *testing.T) {
 	err = binder.Bind(req, RouteParams([]RouteParam{{"id", "1"}}), runtime.JSONConsumer(), &data)
 	require.Error(t, err)
 
-	invalidInParam := spec.HeaderParam("tags").Typed("string", "")
+	invalidInParam := spec.HeaderParam("tags").Typed(typeString, "")
 	invalidInParam.In = "invalid"
 	op5 := map[string]spec.Parameter{"Tags": *invalidInParam}
 	binder = NewUntypedRequestBinder(op5, new(spec.Swagger), strfmt.Default)
@@ -383,7 +383,7 @@ type formRequest struct {
 }
 
 func parametersForFormUpload() map[string]spec.Parameter {
-	nameParam := spec.FormDataParam("name").Typed("string", "")
+	nameParam := spec.FormDataParam("name").Typed(typeString, "")
 
 	ageParam := spec.FormDataParam("age").Typed("integer", "int32")
 
@@ -419,7 +419,7 @@ type fileRequest struct {
 }
 
 func paramsForFileUpload() *UntypedRequestBinder {
-	nameParam := spec.FormDataParam("name").Typed("string", "")
+	nameParam := spec.FormDataParam("name").Typed(typeString, "")
 
 	fileParam := spec.FileParam("file").AsRequired()
 
@@ -506,7 +506,7 @@ func TestBindingFileUpload(t *testing.T) {
 }
 
 func paramsForOptionalFileUpload() *UntypedRequestBinder {
-	nameParam := spec.FormDataParam("name").Typed("string", "")
+	nameParam := spec.FormDataParam("name").Typed(typeString, "")
 	fileParam := spec.FileParam("file").AsOptional()
 
 	params := map[string]spec.Parameter{"Name": *nameParam, "File": *fileParam}
diff --git a/middleware/string_conversion_test.go b/middleware/string_conversion_test.go
index d577d6e..2265b51 100644
--- a/middleware/string_conversion_test.go
+++ b/middleware/string_conversion_test.go
@@ -109,7 +109,7 @@ func TestParamBinding(t *testing.T) {
 	fld := val.FieldByName(pName)
 
 	binder := &untypedParamBinder{
-		parameter: spec.QueryParam(pName).Typed("string", "").WithDefault("some-name"),
+		parameter: spec.QueryParam(pName).Typed(typeString, "").WithDefault("some-name"),
 		Name:      pName,
 	}
 
@@ -172,7 +172,7 @@ func TestParamBinding(t *testing.T) {
 	timeField := val.FieldByName(pName)
 	dt := strfmt.DateTime(time.Date(2014, 3, 19, 2, 9, 0, 0, time.UTC))
 	binder = &untypedParamBinder{
-		parameter: spec.QueryParam(pName).Typed("string", "date-time").WithDefault(dt),
+		parameter: spec.QueryParam(pName).Typed(typeString, "date-time").WithDefault(dt),
 		Name:      pName,
 	}
 	exp := strfmt.DateTime(time.Date(2014, 5, 14, 2, 9, 0, 0, time.UTC))
@@ -192,7 +192,7 @@ func TestParamBinding(t *testing.T) {
 	pName = "Birthdate"
 	dateField := val.FieldByName(pName)
 	binder = &untypedParamBinder{
-		parameter: spec.QueryParam(pName).Typed("string", "date").WithDefault(ddt),
+		parameter: spec.QueryParam(pName).Typed(typeString, "date").WithDefault(ddt),
 		Name:      pName,
 	}
 	expd := strfmt.Date(time.Date(2014, 5, 14, 0, 0, 0, 0, time.UTC))
@@ -213,7 +213,7 @@ func TestParamBinding(t *testing.T) {
 	pName = "LastFailure"
 	ftimeField := val.FieldByName(pName)
 	binder = &untypedParamBinder{
-		parameter: spec.QueryParam(pName).Typed("string", "date").WithDefault(fdt),
+		parameter: spec.QueryParam(pName).Typed(typeString, "date").WithDefault(fdt),
 		Name:      pName,
 	}
 	exp = strfmt.DateTime(time.Date(2014, 5, 14, 2, 9, 0, 0, time.UTC))
@@ -239,7 +239,7 @@ func TestParamBinding(t *testing.T) {
 	pName = "Unsupported"
 	unsupportedField := val.FieldByName(pName)
 	binder = &untypedParamBinder{
-		parameter: spec.QueryParam(pName).Typed("string", ""),
+		parameter: spec.QueryParam(pName).Typed(typeString, ""),
 		Name:      pName,
 	}
 	err = binder.setFieldValue(unsupportedField, nil, "", true)
@@ -255,7 +255,7 @@ func TestSliceConversion(t *testing.T) {
 	// _, _, err := readFormattedSliceFieldValue("Prefs", prefsField, cData, "csv", nil)
 	// require.Error(t, err)
 
-	sliced := []string{"some", "string", "values"}
+	sliced := []string{"some", typeString, "values"}
 	seps := map[string]string{"ssv": " ", "tsv": "\t", "pipes": "|", "csv": ",", "": ","}
 
 	tagsField := val.FieldByName("Tags")
diff --git a/middleware/swaggerui_oauth2_test.go b/middleware/swaggerui_oauth2_test.go
index 7d3796f..c9b28c9 100644
--- a/middleware/swaggerui_oauth2_test.go
+++ b/middleware/swaggerui_oauth2_test.go
@@ -2,6 +2,7 @@ package middleware
 
 import (
 	"context"
+	"fmt"
 	"net/http"
 	"net/http/httptest"
 	"testing"
@@ -19,5 +20,7 @@ func TestSwaggerUIOAuth2CallbackMiddleware(t *testing.T) {
 	redoc.ServeHTTP(recorder, req)
 	assert.Equal(t, http.StatusOK, recorder.Code)
 	assert.Equal(t, "text/html; charset=utf-8", recorder.Header().Get("Content-Type"))
-	assert.Contains(t, recorder.Body.String(), "<title>API documentation</title>")
+	var o SwaggerUIOpts
+	o.EnsureDefaults()
+	assert.Contains(t, recorder.Body.String(), fmt.Sprintf("<title>%s</title>", o.Title))
 }
diff --git a/middleware/swaggerui_test.go b/middleware/swaggerui_test.go
index 0613db0..4047e66 100644
--- a/middleware/swaggerui_test.go
+++ b/middleware/swaggerui_test.go
@@ -2,8 +2,10 @@ package middleware
 
 import (
 	"context"
+	"fmt"
 	"net/http"
 	"net/http/httptest"
+	"strings"
 	"testing"
 
 	"github.com/stretchr/testify/assert"
@@ -11,16 +13,18 @@ import (
 )
 
 func TestSwaggerUIMiddleware(t *testing.T) {
-	redoc := SwaggerUI(SwaggerUIOpts{}, nil)
+	var o SwaggerUIOpts
+	o.EnsureDefaults()
+	swui := SwaggerUI(o, nil)
 
 	req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/docs", nil)
 	require.NoError(t, err)
 	recorder := httptest.NewRecorder()
-	redoc.ServeHTTP(recorder, req)
+	swui.ServeHTTP(recorder, req)
 	assert.Equal(t, http.StatusOK, recorder.Code)
 	assert.Equal(t, "text/html; charset=utf-8", recorder.Header().Get("Content-Type"))
-	assert.Contains(t, recorder.Body.String(), "<title>API documentation</title>")
-	assert.Contains(t, recorder.Body.String(), "url: '\\/swagger.json',")
+	assert.Contains(t, recorder.Body.String(), fmt.Sprintf("<title>%s</title>", o.Title))
+	assert.Contains(t, recorder.Body.String(), fmt.Sprintf(`url: '%s',`, strings.ReplaceAll(o.SpecURL, `/`, `\/`)))
 	assert.Contains(t, recorder.Body.String(), swaggerLatest)
 	assert.Contains(t, recorder.Body.String(), swaggerPresetLatest)
 	assert.Contains(t, recorder.Body.String(), swaggerStylesLatest)
diff --git a/middleware/untyped/api_test.go b/middleware/untyped/api_test.go
index 9c10f9a..fa2a1fe 100644
--- a/middleware/untyped/api_test.go
+++ b/middleware/untyped/api_test.go
@@ -59,7 +59,7 @@ func (s *stubOperationHandler) ParameterModel() interface{} {
 }
 
 func (s *stubOperationHandler) Handle(_ interface{}) (interface{}, error) {
-	return nil, nil //nolint:nilnil
+	return map[string]interface{}{}, nil
 }
 
 func TestUntypedAPIRegistrations(t *testing.T) {
diff --git a/security/apikey_auth_test.go b/security/apikey_auth_test.go
index 8a0c5a7..02b83cd 100644
--- a/security/apikey_auth_test.go
+++ b/security/apikey_auth_test.go
@@ -16,6 +16,7 @@ package security
 
 import (
 	"context"
+	"fmt"
 	"net/http"
 	"testing"
 
@@ -25,181 +26,199 @@ import (
 )
 
 const (
-	apiToken          = "token123"
-	apiTokenPrincipal = "admin"
+	apiKeyParam  = "api_key"
+	apiKeyHeader = "X-API-KEY"
 )
 
-var tokenAuth = TokenAuthentication(func(token string) (interface{}, error) {
-	if token == apiToken {
-		return apiTokenPrincipal, nil
-	}
-	return nil, errors.Unauthenticated("token")
-})
-
-var tokenAuthCtx = TokenAuthenticationCtx(func(ctx context.Context, token string) (context.Context, interface{}, error) {
-	if token == apiToken {
-		return context.WithValue(ctx, extra, extraWisdom), apiTokenPrincipal, nil
-	}
-	return context.WithValue(ctx, reason, expReason), nil, errors.Unauthenticated("token")
-})
-
-func TestInvalidApiKeyAuthInitialization(t *testing.T) {
-	assert.Panics(t, func() { APIKeyAuth("api_key", "qery", tokenAuth) })
+func TestApiKeyAuth(t *testing.T) {
+	tokenAuth := TokenAuthentication(func(token string) (interface{}, error) {
+		if token == validToken {
+			return principal, nil
+		}
+		return nil, errors.Unauthenticated("token")
+	})
+
+	t.Run("with invalid initialization", func(t *testing.T) {
+		assert.Panics(t, func() { APIKeyAuth(apiKeyParam, "qery", tokenAuth) })
+	})
+
+	t.Run("with token in query param", func(t *testing.T) {
+		ta := APIKeyAuth(apiKeyParam, query, tokenAuth)
+
+		t.Run("with valid token", func(t *testing.T) {
+			req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, fmt.Sprintf("%s?%s=%s", authPath, apiKeyParam, validToken), nil)
+			require.NoError(t, err)
+
+			ok, usr, err := ta.Authenticate(req)
+			assert.True(t, ok)
+			assert.Equal(t, principal, usr)
+			require.NoError(t, err)
+		})
+
+		t.Run("with invalid token", func(t *testing.T) {
+			req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, fmt.Sprintf("%s?%s=%s", authPath, apiKeyParam, invalidToken), nil)
+			require.NoError(t, err)
+
+			ok, usr, err := ta.Authenticate(req)
+			assert.True(t, ok)
+			assert.Equal(t, nil, usr)
+			require.Error(t, err)
+		})
+
+		t.Run("with missing token", func(t *testing.T) {
+			// put the token in the header, but query param is expected
+			req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authPath, nil)
+			require.NoError(t, err)
+			req.Header.Set(apiKeyHeader, validToken)
+
+			ok, usr, err := ta.Authenticate(req)
+			assert.False(t, ok)
+			assert.Equal(t, nil, usr)
+			require.NoError(t, err)
+		})
+	})
+
+	t.Run("with token in header", func(t *testing.T) {
+		ta := APIKeyAuth(apiKeyHeader, header, tokenAuth)
+
+		t.Run("with valid token", func(t *testing.T) {
+			req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authPath, nil)
+			require.NoError(t, err)
+			req.Header.Set(apiKeyHeader, validToken)
+
+			ok, usr, err := ta.Authenticate(req)
+			assert.True(t, ok)
+			assert.Equal(t, principal, usr)
+			require.NoError(t, err)
+		})
+
+		t.Run("with invalid token", func(t *testing.T) {
+			req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authPath, nil)
+			require.NoError(t, err)
+			req.Header.Set(apiKeyHeader, invalidToken)
+
+			ok, usr, err := ta.Authenticate(req)
+			assert.True(t, ok)
+			assert.Equal(t, nil, usr)
+			require.Error(t, err)
+		})
+
+		t.Run("with missing token", func(t *testing.T) {
+			// put the token in the query param, but header is expected
+			req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, fmt.Sprintf("%s?%s=%s", authPath, apiKeyParam, validToken), nil)
+			require.NoError(t, err)
+
+			ok, usr, err := ta.Authenticate(req)
+			assert.False(t, ok)
+			assert.Equal(t, nil, usr)
+			require.NoError(t, err)
+		})
+	})
 }
 
-func TestValidApiKeyAuth(t *testing.T) {
-	ta := APIKeyAuth("api_key", "query", tokenAuth)
-	ta2 := APIKeyAuth("X-API-KEY", "header", tokenAuth)
-
-	req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?api_key=token123", nil)
-	require.NoError(t, err)
-
-	ok, usr, err := ta.Authenticate(req1)
-	assert.True(t, ok)
-	assert.Equal(t, apiTokenPrincipal, usr)
-	require.NoError(t, err)
-
-	req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil)
-	require.NoError(t, err)
-	req2.Header.Set("X-API-KEY", apiToken)
-
-	ok, usr, err = ta2.Authenticate(req2)
-	assert.True(t, ok)
-	assert.Equal(t, apiTokenPrincipal, usr)
-	require.NoError(t, err)
-}
-
-func TestInvalidApiKeyAuth(t *testing.T) {
-	ta := APIKeyAuth("api_key", "query", tokenAuth)
-	ta2 := APIKeyAuth("X-API-KEY", "header", tokenAuth)
-
-	req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?api_key=token124", nil)
-	require.NoError(t, err)
-
-	ok, usr, err := ta.Authenticate(req1)
-	assert.True(t, ok)
-	assert.Equal(t, nil, usr)
-	require.Error(t, err)
-
-	req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil)
-	require.NoError(t, err)
-	req2.Header.Set("X-API-KEY", "token124")
-
-	ok, usr, err = ta2.Authenticate(req2)
-	assert.True(t, ok)
-	assert.Equal(t, nil, usr)
-	require.Error(t, err)
-}
-
-func TestMissingApiKeyAuth(t *testing.T) {
-	ta := APIKeyAuth("api_key", "query", tokenAuth)
-	ta2 := APIKeyAuth("X-API-KEY", "header", tokenAuth)
-
-	req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil)
-	require.NoError(t, err)
-	req1.Header.Set("X-API-KEY", apiToken)
-
-	ok, usr, err := ta.Authenticate(req1)
-	assert.False(t, ok)
-	assert.Equal(t, nil, usr)
-	require.NoError(t, err)
-
-	req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?api_key=token123", nil)
-	require.NoError(t, err)
-
-	ok, usr, err = ta2.Authenticate(req2)
-	assert.False(t, ok)
-	assert.Equal(t, nil, usr)
-	require.NoError(t, err)
-}
-
-func TestInvalidApiKeyAuthInitializationCtx(t *testing.T) {
-	assert.Panics(t, func() { APIKeyAuthCtx("api_key", "qery", tokenAuthCtx) })
-}
-
-func TestValidApiKeyAuthCtx(t *testing.T) {
-	ta := APIKeyAuthCtx("api_key", "query", tokenAuthCtx)
-	ta2 := APIKeyAuthCtx("X-API-KEY", "header", tokenAuthCtx)
-
-	req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?api_key=token123", nil)
-	require.NoError(t, err)
-	req1 = req1.WithContext(context.WithValue(req1.Context(), original, wisdom))
-	ok, usr, err := ta.Authenticate(req1)
-	assert.True(t, ok)
-	assert.Equal(t, apiTokenPrincipal, usr)
-	require.NoError(t, err)
-	assert.Equal(t, wisdom, req1.Context().Value(original))
-	assert.Equal(t, extraWisdom, req1.Context().Value(extra))
-	assert.Nil(t, req1.Context().Value(reason))
-
-	req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil)
-	require.NoError(t, err)
-	req2 = req2.WithContext(context.WithValue(req2.Context(), original, wisdom))
-	req2.Header.Set("X-API-KEY", apiToken)
-
-	ok, usr, err = ta2.Authenticate(req2)
-	assert.True(t, ok)
-	assert.Equal(t, apiTokenPrincipal, usr)
-	require.NoError(t, err)
-	assert.Equal(t, wisdom, req2.Context().Value(original))
-	assert.Equal(t, extraWisdom, req2.Context().Value(extra))
-	assert.Nil(t, req2.Context().Value(reason))
-}
-
-func TestInvalidApiKeyAuthCtx(t *testing.T) {
-	ta := APIKeyAuthCtx("api_key", "query", tokenAuthCtx)
-	ta2 := APIKeyAuthCtx("X-API-KEY", "header", tokenAuthCtx)
-
-	req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?api_key=token124", nil)
-	require.NoError(t, err)
-	req1 = req1.WithContext(context.WithValue(req1.Context(), original, wisdom))
-	ok, usr, err := ta.Authenticate(req1)
-	assert.True(t, ok)
-	assert.Equal(t, nil, usr)
-	require.Error(t, err)
-	assert.Equal(t, wisdom, req1.Context().Value(original))
-	assert.Equal(t, expReason, req1.Context().Value(reason))
-	assert.Nil(t, req1.Context().Value(extra))
-
-	req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil)
-	require.NoError(t, err)
-	req2 = req2.WithContext(context.WithValue(req2.Context(), original, wisdom))
-	req2.Header.Set("X-API-KEY", "token124")
-
-	ok, usr, err = ta2.Authenticate(req2)
-	assert.True(t, ok)
-	assert.Equal(t, nil, usr)
-	require.Error(t, err)
-	assert.Equal(t, wisdom, req2.Context().Value(original))
-	assert.Equal(t, expReason, req2.Context().Value(reason))
-	assert.Nil(t, req2.Context().Value(extra))
-}
-
-func TestMissingApiKeyAuthCtx(t *testing.T) {
-	ta := APIKeyAuthCtx("api_key", "query", tokenAuthCtx)
-	ta2 := APIKeyAuthCtx("X-API-KEY", "header", tokenAuthCtx)
-
-	req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil)
-	require.NoError(t, err)
-	req1 = req1.WithContext(context.WithValue(req1.Context(), original, wisdom))
-	req1.Header.Set("X-API-KEY", apiToken)
-
-	ok, usr, err := ta.Authenticate(req1)
-	assert.False(t, ok)
-	assert.Equal(t, nil, usr)
-	require.NoError(t, err)
-	assert.Equal(t, wisdom, req1.Context().Value(original))
-	assert.Nil(t, req1.Context().Value(reason))
-	assert.Nil(t, req1.Context().Value(extra))
-
-	req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?api_key=token123", nil)
-	require.NoError(t, err)
-	req2 = req2.WithContext(context.WithValue(req2.Context(), original, wisdom))
-	ok, usr, err = ta2.Authenticate(req2)
-	assert.False(t, ok)
-	assert.Equal(t, nil, usr)
-	require.NoError(t, err)
-	assert.Equal(t, wisdom, req2.Context().Value(original))
-	assert.Nil(t, req2.Context().Value(reason))
-	assert.Nil(t, req2.Context().Value(extra))
+func TestApiKeyAuthCtx(t *testing.T) {
+	tokenAuthCtx := TokenAuthenticationCtx(func(ctx context.Context, token string) (context.Context, interface{}, error) {
+		if token == validToken {
+			return context.WithValue(ctx, extra, extraWisdom), principal, nil
+		}
+		return context.WithValue(ctx, reason, expReason), nil, errors.Unauthenticated("token")
+	})
+	ctx := context.WithValue(context.Background(), original, wisdom)
+
+	t.Run("with invalid initialization", func(t *testing.T) {
+		assert.Panics(t, func() { APIKeyAuthCtx(apiKeyParam, "qery", tokenAuthCtx) })
+	})
+
+	t.Run("with token in query param", func(t *testing.T) {
+		ta := APIKeyAuthCtx(apiKeyParam, query, tokenAuthCtx)
+
+		t.Run("with valid token", func(t *testing.T) {
+			req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s?%s=%s", authPath, apiKeyParam, validToken), nil)
+			require.NoError(t, err)
+			ok, usr, err := ta.Authenticate(req)
+			assert.True(t, ok)
+			assert.Equal(t, principal, usr)
+			require.NoError(t, err)
+
+			assert.Equal(t, wisdom, req.Context().Value(original))
+			assert.Equal(t, extraWisdom, req.Context().Value(extra))
+			assert.Nil(t, req.Context().Value(reason))
+		})
+
+		t.Run("with invalid token", func(t *testing.T) {
+			req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s?%s=%s", authPath, apiKeyParam, invalidToken), nil)
+			require.NoError(t, err)
+			ok, usr, err := ta.Authenticate(req)
+			assert.True(t, ok)
+			assert.Equal(t, nil, usr)
+			require.Error(t, err)
+
+			assert.Equal(t, wisdom, req.Context().Value(original))
+			assert.Equal(t, expReason, req.Context().Value(reason))
+			assert.Nil(t, req.Context().Value(extra))
+		})
+
+		t.Run("with missing token", func(t *testing.T) {
+			req, err := http.NewRequestWithContext(ctx, http.MethodGet, authPath, nil)
+			require.NoError(t, err)
+			req.Header.Set(apiKeyHeader, validToken)
+
+			ok, usr, err := ta.Authenticate(req)
+			assert.False(t, ok)
+			assert.Equal(t, nil, usr)
+			require.NoError(t, err)
+
+			assert.Equal(t, wisdom, req.Context().Value(original))
+			assert.Nil(t, req.Context().Value(reason))
+			assert.Nil(t, req.Context().Value(extra))
+		})
+	})
+
+	t.Run("with token in header", func(t *testing.T) {
+		ta := APIKeyAuthCtx(apiKeyHeader, header, tokenAuthCtx)
+
+		t.Run("with valid token", func(t *testing.T) {
+			req, err := http.NewRequestWithContext(ctx, http.MethodGet, authPath, nil)
+			require.NoError(t, err)
+			req.Header.Set(apiKeyHeader, validToken)
+
+			ok, usr, err := ta.Authenticate(req)
+			assert.True(t, ok)
+			assert.Equal(t, principal, usr)
+			require.NoError(t, err)
+
+			assert.Equal(t, wisdom, req.Context().Value(original))
+			assert.Equal(t, extraWisdom, req.Context().Value(extra))
+			assert.Nil(t, req.Context().Value(reason))
+		})
+
+		t.Run("with invalid token", func(t *testing.T) {
+			req, err := http.NewRequestWithContext(ctx, http.MethodGet, authPath, nil)
+			require.NoError(t, err)
+			req.Header.Set(apiKeyHeader, invalidToken)
+
+			ok, usr, err := ta.Authenticate(req)
+			assert.True(t, ok)
+			assert.Equal(t, nil, usr)
+			require.Error(t, err)
+
+			assert.Equal(t, wisdom, req.Context().Value(original))
+			assert.Equal(t, expReason, req.Context().Value(reason))
+			assert.Nil(t, req.Context().Value(extra))
+		})
+
+		t.Run("with missing token", func(t *testing.T) {
+			req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("%s?%s=%s", authPath, apiKeyParam, validToken), nil)
+			require.NoError(t, err)
+
+			ok, usr, err := ta.Authenticate(req)
+			assert.False(t, ok)
+			assert.Equal(t, nil, usr)
+			require.NoError(t, err)
+
+			assert.Equal(t, wisdom, req.Context().Value(original))
+			assert.Nil(t, req.Context().Value(reason))
+			assert.Nil(t, req.Context().Value(extra))
+		})
+	})
 }
diff --git a/security/authorizer_test.go b/security/authorizer_test.go
index 92eb1e3..5463748 100644
--- a/security/authorizer_test.go
+++ b/security/authorizer_test.go
@@ -15,8 +15,11 @@
 package security
 
 import (
+	"context"
+	"net/http"
 	"testing"
 
+	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
 )
 
@@ -26,3 +29,55 @@ func TestAuthorized(t *testing.T) {
 	err := authorizer.Authorize(nil, nil)
 	require.NoError(t, err)
 }
+
+func TestAuthenticator(t *testing.T) {
+	r, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/", nil)
+	require.NoError(t, err)
+
+	t.Run("with HttpAuthenticator", func(t *testing.T) {
+		auth := HttpAuthenticator(func(_ *http.Request) (bool, interface{}, error) { return true, "test", nil })
+
+		t.Run("authenticator should work on *http.Request", func(t *testing.T) {
+			isAuth, user, err := auth.Authenticate(r)
+			require.NoError(t, err)
+			assert.True(t, isAuth)
+			assert.Equal(t, "test", user)
+		})
+
+		t.Run("authenticator should work on *ScopedAuthRequest", func(t *testing.T) {
+			scoped := &ScopedAuthRequest{Request: r}
+
+			isAuth, user, err := auth.Authenticate(scoped)
+			require.NoError(t, err)
+			assert.True(t, isAuth)
+			assert.Equal(t, "test", user)
+		})
+
+		t.Run("authenticator should return false on other inputs", func(t *testing.T) {
+			isAuth, user, err := auth.Authenticate("")
+			require.NoError(t, err)
+			assert.False(t, isAuth)
+			assert.Empty(t, user)
+		})
+	})
+
+	t.Run("with ScopedAuthenticator", func(t *testing.T) {
+		auth := ScopedAuthenticator(func(_ *ScopedAuthRequest) (bool, interface{}, error) { return true, "test", nil })
+
+		t.Run("authenticator should work on *ScopedAuthRequest", func(t *testing.T) {
+			scoped := &ScopedAuthRequest{Request: r}
+
+			isAuth, user, err := auth.Authenticate(scoped)
+			require.NoError(t, err)
+			assert.True(t, isAuth)
+			assert.Equal(t, "test", user)
+		})
+
+		t.Run("authenticator should return false on other inputs", func(t *testing.T) {
+			isAuth, user, err := auth.Authenticate("")
+			require.NoError(t, err)
+			assert.False(t, isAuth)
+			assert.Empty(t, user)
+		})
+	})
+}
diff --git a/security/basic_auth_test.go b/security/basic_auth_test.go
index 1e5f12f..8a90451 100644
--- a/security/basic_auth_test.go
+++ b/security/basic_auth_test.go
@@ -33,137 +33,181 @@ const (
 )
 
 const (
-	wisdom            = "The man who is swimming against the stream knows the strength of it."
-	extraWisdom       = "Our greatest glory is not in never falling, but in rising every time we fall."
-	expReason         = "I like the dreams of the future better than the history of the past."
-	authenticatedPath = "/blah"
-	testPassword      = "123456"
-	basicPrincipal    = "admin"
+	wisdom       = "The man who is swimming against the stream knows the strength of it."
+	extraWisdom  = "Our greatest glory is not in never falling, but in rising every time we fall."
+	expReason    = "I like the dreams of the future better than the history of the past."
+	testPassword = "123456"
 )
 
-var basicAuthHandler = UserPassAuthentication(func(user, pass string) (interface{}, error) {
-	if user == basicPrincipal && pass == testPassword {
-		return basicPrincipal, nil
-	}
-	return "", errors.Unauthenticated("basic")
-})
-
-func TestValidBasicAuth(t *testing.T) {
-	ba := BasicAuth(basicAuthHandler)
-
-	req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authenticatedPath, nil)
-	require.NoError(t, err)
-
-	req.SetBasicAuth(basicPrincipal, testPassword)
-	ok, usr, err := ba.Authenticate(req)
-	require.NoError(t, err)
-	assert.True(t, ok)
-	assert.Equal(t, basicPrincipal, usr)
-}
-
-func TestInvalidBasicAuth(t *testing.T) {
-	ba := BasicAuth(basicAuthHandler)
-
-	req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authenticatedPath, nil)
-	require.NoError(t, err)
-	req.SetBasicAuth(basicPrincipal, basicPrincipal)
-
-	ok, usr, err := ba.Authenticate(req)
-	require.Error(t, err)
-	assert.True(t, ok)
-	assert.Equal(t, "", usr)
-
-	assert.NotEmpty(t, FailedBasicAuth(req))
-	assert.Equal(t, DefaultRealmName, FailedBasicAuth(req))
-}
-
-func TestMissingbasicAuth(t *testing.T) {
-	ba := BasicAuth(basicAuthHandler)
-
-	req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authenticatedPath, nil)
-	require.NoError(t, err)
-
-	ok, usr, err := ba.Authenticate(req)
-	require.NoError(t, err)
-	assert.False(t, ok)
-	assert.Equal(t, nil, usr)
-
-	assert.NotEmpty(t, FailedBasicAuth(req))
-	assert.Equal(t, DefaultRealmName, FailedBasicAuth(req))
-}
-
-func TestNoRequestBasicAuth(t *testing.T) {
+func TestBasicAuth(t *testing.T) {
+	basicAuthHandler := UserPassAuthentication(func(user, pass string) (interface{}, error) {
+		if user == principal && pass == testPassword {
+			return principal, nil
+		}
+		return "", errors.Unauthenticated("basic")
+	})
 	ba := BasicAuth(basicAuthHandler)
 
-	ok, usr, err := ba.Authenticate("token")
-	require.NoError(t, err)
-	assert.False(t, ok)
-	assert.Nil(t, usr)
+	t.Run("with valid basic auth", func(t *testing.T) {
+		req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authPath, nil)
+		require.NoError(t, err)
+		req.SetBasicAuth(principal, testPassword)
+
+		ok, usr, err := ba.Authenticate(req)
+		require.NoError(t, err)
+		assert.True(t, ok)
+		assert.Equal(t, principal, usr)
+	})
+
+	t.Run("with invalid basic auth", func(t *testing.T) {
+		req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authPath, nil)
+		require.NoError(t, err)
+		req.SetBasicAuth(principal, principal)
+
+		ok, usr, err := ba.Authenticate(req)
+		require.Error(t, err)
+		assert.True(t, ok)
+		assert.Equal(t, "", usr)
+
+		assert.NotEmpty(t, FailedBasicAuth(req))
+		assert.Equal(t, DefaultRealmName, FailedBasicAuth(req))
+	})
+
+	t.Run("with missing basic auth", func(t *testing.T) {
+		req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authPath, nil)
+		require.NoError(t, err)
+
+		ok, usr, err := ba.Authenticate(req)
+		require.NoError(t, err)
+		assert.False(t, ok)
+		assert.Equal(t, nil, usr)
+
+		assert.NotEmpty(t, FailedBasicAuth(req))
+		assert.Equal(t, DefaultRealmName, FailedBasicAuth(req))
+	})
+
+	t.Run("basic auth without request", func(*testing.T) {
+		ok, usr, err := ba.Authenticate("token")
+		require.NoError(t, err)
+		assert.False(t, ok)
+		assert.Nil(t, usr)
+	})
+
+	t.Run("with realm, invalid basic auth", func(t *testing.T) {
+		br := BasicAuthRealm("realm", basicAuthHandler)
+
+		req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authPath, nil)
+		require.NoError(t, err)
+		req.SetBasicAuth(principal, principal)
+
+		ok, usr, err := br.Authenticate(req)
+		require.Error(t, err)
+		assert.True(t, ok)
+		assert.Equal(t, "", usr)
+		assert.Equal(t, "realm", FailedBasicAuth(req))
+	})
+
+	t.Run("with empty realm, invalid basic auth", func(t *testing.T) {
+		br := BasicAuthRealm("", basicAuthHandler)
+
+		req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authPath, nil)
+		require.NoError(t, err)
+		req.SetBasicAuth(principal, principal)
+
+		ok, usr, err := br.Authenticate(req)
+		require.Error(t, err)
+		assert.True(t, ok)
+		assert.Equal(t, "", usr)
+		assert.Equal(t, DefaultRealmName, FailedBasicAuth(req))
+	})
 }
 
-var basicAuthHandlerCtx = UserPassAuthenticationCtx(func(ctx context.Context, user, pass string) (context.Context, interface{}, error) {
-	if user == basicPrincipal && pass == testPassword {
-		return context.WithValue(ctx, extra, extraWisdom), basicPrincipal, nil
-	}
-	return context.WithValue(ctx, reason, expReason), "", errors.Unauthenticated("basic")
-})
-
-func TestValidBasicAuthCtx(t *testing.T) {
+func TestBasicAuthCtx(t *testing.T) {
+	basicAuthHandlerCtx := UserPassAuthenticationCtx(func(ctx context.Context, user, pass string) (context.Context, interface{}, error) {
+		if user == principal && pass == testPassword {
+			return context.WithValue(ctx, extra, extraWisdom), principal, nil
+		}
+		return context.WithValue(ctx, reason, expReason), "", errors.Unauthenticated("basic")
+	})
 	ba := BasicAuthCtx(basicAuthHandlerCtx)
-
-	req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authenticatedPath, nil)
-	require.NoError(t, err)
-	req = req.WithContext(context.WithValue(req.Context(), original, wisdom))
-
-	req.SetBasicAuth(basicPrincipal, testPassword)
-	ok, usr, err := ba.Authenticate(req)
-	require.NoError(t, err)
-	assert.True(t, ok)
-	assert.Equal(t, basicPrincipal, usr)
-	assert.Equal(t, wisdom, req.Context().Value(original))
-	assert.Equal(t, extraWisdom, req.Context().Value(extra))
-	assert.Nil(t, req.Context().Value(reason))
-}
-
-func TestInvalidBasicAuthCtx(t *testing.T) {
-	ba := BasicAuthCtx(basicAuthHandlerCtx)
-
-	req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authenticatedPath, nil)
-	require.NoError(t, err)
-	req = req.WithContext(context.WithValue(req.Context(), original, wisdom))
-	req.SetBasicAuth(basicPrincipal, basicPrincipal)
-
-	ok, usr, err := ba.Authenticate(req)
-	require.Error(t, err)
-	assert.True(t, ok)
-	assert.Equal(t, "", usr)
-	assert.Equal(t, wisdom, req.Context().Value(original))
-	assert.Nil(t, req.Context().Value(extra))
-	assert.Equal(t, expReason, req.Context().Value(reason))
-}
-
-func TestMissingbasicAuthCtx(t *testing.T) {
-	ba := BasicAuthCtx(basicAuthHandlerCtx)
-
-	req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authenticatedPath, nil)
-	require.NoError(t, err)
-	req = req.WithContext(context.WithValue(req.Context(), original, wisdom))
-
-	ok, usr, err := ba.Authenticate(req)
-	require.NoError(t, err)
-	assert.False(t, ok)
-	assert.Equal(t, nil, usr)
-
-	assert.Equal(t, wisdom, req.Context().Value(original))
-	assert.Nil(t, req.Context().Value(extra))
-	assert.Nil(t, req.Context().Value(reason))
-}
-
-func TestNoRequestBasicAuthCtx(t *testing.T) {
-	ba := BasicAuthCtx(basicAuthHandlerCtx)
-
-	ok, usr, err := ba.Authenticate("token")
-	require.NoError(t, err)
-	assert.False(t, ok)
-	assert.Nil(t, usr)
+	ctx := context.WithValue(context.Background(), original, wisdom)
+
+	t.Run("with valid basic auth", func(t *testing.T) {
+		req, err := http.NewRequestWithContext(ctx, http.MethodGet, authPath, nil)
+		require.NoError(t, err)
+
+		req.SetBasicAuth(principal, testPassword)
+		ok, usr, err := ba.Authenticate(req)
+		require.NoError(t, err)
+		assert.True(t, ok)
+		assert.Equal(t, principal, usr)
+
+		assert.Equal(t, wisdom, req.Context().Value(original))
+		assert.Equal(t, extraWisdom, req.Context().Value(extra))
+		assert.Nil(t, req.Context().Value(reason))
+	})
+
+	t.Run("with invalid basic auth", func(t *testing.T) {
+		req, err := http.NewRequestWithContext(ctx, http.MethodGet, authPath, nil)
+		require.NoError(t, err)
+		req.SetBasicAuth(principal, principal)
+
+		ok, usr, err := ba.Authenticate(req)
+		require.Error(t, err)
+		assert.True(t, ok)
+		assert.Equal(t, "", usr)
+
+		assert.Equal(t, wisdom, req.Context().Value(original))
+		assert.Nil(t, req.Context().Value(extra))
+		assert.Equal(t, expReason, req.Context().Value(reason))
+	})
+
+	t.Run("with missing basic auth", func(t *testing.T) {
+		req, err := http.NewRequestWithContext(ctx, http.MethodGet, authPath, nil)
+		require.NoError(t, err)
+
+		ok, usr, err := ba.Authenticate(req)
+		require.NoError(t, err)
+		assert.False(t, ok)
+		assert.Equal(t, nil, usr)
+
+		assert.Equal(t, wisdom, req.Context().Value(original))
+		assert.Nil(t, req.Context().Value(extra))
+		assert.Nil(t, req.Context().Value(reason))
+	})
+
+	t.Run("basic auth without request", func(*testing.T) {
+		ok, usr, err := ba.Authenticate("token")
+		require.NoError(t, err)
+		assert.False(t, ok)
+		assert.Nil(t, usr)
+	})
+
+	t.Run("with realm, invalid basic auth", func(t *testing.T) {
+		br := BasicAuthRealmCtx("realm", basicAuthHandlerCtx)
+
+		req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authPath, nil)
+		require.NoError(t, err)
+		req.SetBasicAuth(principal, principal)
+
+		ok, usr, err := br.Authenticate(req)
+		require.Error(t, err)
+		assert.True(t, ok)
+		assert.Equal(t, "", usr)
+		assert.Equal(t, "realm", FailedBasicAuth(req))
+	})
+
+	t.Run("with empty realm, invalid basic auth", func(t *testing.T) {
+		br := BasicAuthRealmCtx("", basicAuthHandlerCtx)
+
+		req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, authPath, nil)
+		require.NoError(t, err)
+		req.SetBasicAuth(principal, principal)
+
+		ok, usr, err := br.Authenticate(req)
+		require.Error(t, err)
+		assert.True(t, ok)
+		assert.Equal(t, "", usr)
+		assert.Equal(t, DefaultRealmName, FailedBasicAuth(req))
+	})
 }
diff --git a/security/bearer_auth_test.go b/security/bearer_auth_test.go
index 476d35b..42ff57b 100644
--- a/security/bearer_auth_test.go
+++ b/security/bearer_auth_test.go
@@ -3,6 +3,7 @@ package security
 import (
 	"bytes"
 	"context"
+	"fmt"
 	"mime/multipart"
 	"net/http"
 	"net/url"
@@ -15,343 +16,285 @@ import (
 	"github.com/stretchr/testify/require"
 )
 
-var bearerAuth = ScopedTokenAuthentication(func(token string, _ []string) (interface{}, error) {
-	if token == "token123" {
-		return "admin", nil
+const (
+	owners       = "owners_auth"
+	validToken   = "token123"
+	invalidToken = "token124"
+	principal    = "admin"
+	authPath     = "/blah"
+	invalidParam = "access_toke"
+)
+
+type authExpectation uint8
+
+const (
+	expectIsAuthorized authExpectation = iota
+	expectInvalidAuthorization
+	expectNoAuthorization
+)
+
+func TestBearerAuth(t *testing.T) {
+	bearerAuth := ScopedTokenAuthentication(func(token string, _ []string) (interface{}, error) {
+		if token == validToken {
+			return principal, nil
+		}
+		return nil, errors.Unauthenticated("bearer")
+	})
+	ba := BearerAuth(owners, bearerAuth)
+	ctx := context.Background()
+
+	t.Run("with valid bearer auth", func(t *testing.T) {
+		t.Run("token in query param",
+			testAuthenticateBearerInQuery(ctx, ba, "", validToken, expectIsAuthorized),
+		)
+		t.Run("token in header",
+			testAuthenticateBearerInHeader(ctx, ba, "", validToken, expectIsAuthorized),
+		)
+		t.Run("token in urlencoded form",
+			testAuthenticateBearerInForm(ctx, ba, "", validToken, expectIsAuthorized),
+		)
+		t.Run("token in multipart form",
+			testAuthenticateBearerInMultipartForm(ctx, ba, "", validToken, expectIsAuthorized),
+		)
+	})
+
+	t.Run("with invalid token", func(t *testing.T) {
+		t.Run("token in query param",
+			testAuthenticateBearerInQuery(ctx, ba, "", invalidToken, expectInvalidAuthorization),
+		)
+		t.Run("token in header",
+			testAuthenticateBearerInHeader(ctx, ba, "", invalidToken, expectInvalidAuthorization),
+		)
+		t.Run("token in urlencoded form",
+			testAuthenticateBearerInForm(ctx, ba, "", invalidToken, expectInvalidAuthorization),
+		)
+		t.Run("token in multipart form",
+			testAuthenticateBearerInMultipartForm(ctx, ba, "", invalidToken, expectInvalidAuthorization),
+		)
+	})
+
+	t.Run("with missing auth", func(t *testing.T) {
+		t.Run("token in query param",
+			testAuthenticateBearerInQuery(ctx, ba, invalidParam, validToken, expectNoAuthorization),
+		)
+		t.Run("token in header",
+			testAuthenticateBearerInHeader(ctx, ba, "Beare", validToken, expectNoAuthorization),
+		)
+		t.Run("token in urlencoded form",
+			testAuthenticateBearerInForm(ctx, ba, invalidParam, validToken, expectNoAuthorization),
+		)
+		t.Run("token in multipart form",
+			testAuthenticateBearerInMultipartForm(ctx, ba, invalidParam, validToken, expectNoAuthorization),
+		)
+	})
+}
+
+func TestBearerAuthCtx(t *testing.T) {
+	bearerAuthCtx := ScopedTokenAuthenticationCtx(func(ctx context.Context, token string, _ []string) (context.Context, interface{}, error) {
+		if token == validToken {
+			return context.WithValue(ctx, extra, extraWisdom), principal, nil
+		}
+		return context.WithValue(ctx, reason, expReason), nil, errors.Unauthenticated("bearer")
+	})
+	ba := BearerAuthCtx(owners, bearerAuthCtx)
+	ctx := context.WithValue(context.Background(), original, wisdom)
+
+	assertContextOK := func(requestContext context.Context, t *testing.T) {
+		// when authorized, we have an "extra" key in context
+		assert.Equal(t, wisdom, requestContext.Value(original))
+		assert.Equal(t, extraWisdom, requestContext.Value(extra))
+		assert.Nil(t, requestContext.Value(reason))
+	}
+
+	assertContextKO := func(requestContext context.Context, t *testing.T) {
+		// when not authorized, we have a "reason" key in context
+		assert.Equal(t, wisdom, requestContext.Value(original))
+		assert.Nil(t, requestContext.Value(extra))
+		assert.Equal(t, expReason, requestContext.Value(reason))
+	}
+
+	assertContextNone := func(requestContext context.Context, t *testing.T) {
+		// when missing authorization, we only have the original context
+		assert.Equal(t, wisdom, requestContext.Value(original))
+		assert.Nil(t, requestContext.Value(extra))
+		assert.Nil(t, requestContext.Value(reason))
+	}
+
+	t.Run("with valid bearer auth", func(t *testing.T) {
+		t.Run("token in query param",
+			testAuthenticateBearerInQuery(ctx, ba, "", validToken, expectIsAuthorized, assertContextOK),
+		)
+		t.Run("token in header",
+			testAuthenticateBearerInHeader(ctx, ba, "", validToken, expectIsAuthorized, assertContextOK),
+		)
+		t.Run("token in urlencoded form",
+			testAuthenticateBearerInForm(ctx, ba, "", validToken, expectIsAuthorized, assertContextOK),
+		)
+		t.Run("token in multipart form",
+			testAuthenticateBearerInMultipartForm(ctx, ba, "", validToken, expectIsAuthorized, assertContextOK),
+		)
+	})
+
+	t.Run("with invalid token", func(t *testing.T) {
+		t.Run("token in query param",
+			testAuthenticateBearerInQuery(ctx, ba, "", invalidToken, expectInvalidAuthorization, assertContextKO),
+		)
+		t.Run("token in header",
+			testAuthenticateBearerInHeader(ctx, ba, "", invalidToken, expectInvalidAuthorization, assertContextKO),
+		)
+		t.Run("token in urlencoded form",
+			testAuthenticateBearerInForm(ctx, ba, "", invalidToken, expectInvalidAuthorization, assertContextKO),
+		)
+		t.Run("token in multipart form",
+			testAuthenticateBearerInMultipartForm(ctx, ba, "", invalidToken, expectInvalidAuthorization, assertContextKO),
+		)
+	})
+
+	t.Run("with missing auth", func(t *testing.T) {
+		t.Run("token in query param",
+			testAuthenticateBearerInQuery(ctx, ba, invalidParam, validToken, expectNoAuthorization, assertContextNone),
+		)
+		t.Run("token in header",
+			testAuthenticateBearerInHeader(ctx, ba, "Beare", validToken, expectNoAuthorization, assertContextNone),
+		)
+		t.Run("token in urlencoded form",
+			testAuthenticateBearerInForm(ctx, ba, invalidParam, validToken, expectNoAuthorization, assertContextNone),
+		)
+		t.Run("token in multipart form",
+			testAuthenticateBearerInMultipartForm(ctx, ba, invalidParam, validToken, expectNoAuthorization, assertContextNone),
+		)
+	})
+}
+
+func testIsAuthorized(_ context.Context, req *http.Request, authorizer runtime.Authenticator, expectAuthorized authExpectation, extraAsserters ...func(context.Context, *testing.T)) func(*testing.T) {
+	return func(t *testing.T) {
+		hasToken, usr, err := authorizer.Authenticate(&ScopedAuthRequest{Request: req})
+		switch expectAuthorized {
+
+		case expectIsAuthorized:
+			require.NoError(t, err)
+			assert.True(t, hasToken)
+			assert.Equal(t, principal, usr)
+			assert.Equal(t, owners, OAuth2SchemeName(req))
+
+		case expectInvalidAuthorization:
+			require.Error(t, err)
+			require.ErrorContains(t, err, "unauthenticated")
+			assert.True(t, hasToken)
+			assert.Nil(t, usr)
+			assert.Equal(t, owners, OAuth2SchemeName(req))
+
+		case expectNoAuthorization:
+			require.NoError(t, err)
+			assert.False(t, hasToken)
+			assert.Nil(t, usr)
+			assert.Empty(t, OAuth2SchemeName(req))
+		}
+
+		for _, contextAsserter := range extraAsserters {
+			contextAsserter(req.Context(), t)
+		}
 	}
-	return nil, errors.Unauthenticated("bearer")
-})
-
-func TestValidBearerAuth(t *testing.T) {
-	ba := BearerAuth("owners_auth", bearerAuth)
-
-	req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?access_token=token123", nil)
-	require.NoError(t, err)
-
-	ok, usr, err := ba.Authenticate(&ScopedAuthRequest{Request: req1})
-	assert.True(t, ok)
-	assert.Equal(t, "admin", usr)
-	require.NoError(t, err)
-	assert.Equal(t, "owners_auth", OAuth2SchemeName(req1))
-
-	req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil)
-	require.NoError(t, err)
-	req2.Header.Set(runtime.HeaderAuthorization, "Bearer token123")
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2})
-	assert.True(t, ok)
-	assert.Equal(t, "admin", usr)
-	require.NoError(t, err)
-	assert.Equal(t, "owners_auth", OAuth2SchemeName(req2))
-
-	body := url.Values(map[string][]string{})
-	body.Set("access_token", "token123")
-	req3, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", strings.NewReader(body.Encode()))
-	require.NoError(t, err)
-	req3.Header.Set("Content-Type", "application/x-www-form-urlencoded")
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req3})
-	assert.True(t, ok)
-	assert.Equal(t, "admin", usr)
-	require.NoError(t, err)
-	assert.Equal(t, "owners_auth", OAuth2SchemeName(req3))
-
-	mpbody := bytes.NewBuffer(nil)
-	writer := multipart.NewWriter(mpbody)
-	err = writer.WriteField("access_token", "token123")
-	require.NoError(t, err)
-	writer.Close()
-	req4, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", mpbody)
-	require.NoError(t, err)
-	req4.Header.Set("Content-Type", writer.FormDataContentType())
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req4})
-	assert.True(t, ok)
-	assert.Equal(t, "admin", usr)
-	require.NoError(t, err)
-	assert.Equal(t, "owners_auth", OAuth2SchemeName(req4))
 }
 
-//nolint:dupl
-func TestInvalidBearerAuth(t *testing.T) {
-	ba := BearerAuth("owners_auth", bearerAuth)
-
-	req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?access_token=token124", nil)
-	require.NoError(t, err)
-
-	ok, usr, err := ba.Authenticate(&ScopedAuthRequest{Request: req1})
-	assert.True(t, ok)
-	assert.Equal(t, nil, usr)
-	require.Error(t, err)
-
-	req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil)
-	require.NoError(t, err)
-	req2.Header.Set(runtime.HeaderAuthorization, "Bearer token124")
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2})
-	assert.True(t, ok)
-	assert.Equal(t, nil, usr)
-	require.Error(t, err)
-
-	body := url.Values(map[string][]string{})
-	body.Set("access_token", "token124")
-	req3, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", strings.NewReader(body.Encode()))
-	require.NoError(t, err)
-	req3.Header.Set("Content-Type", "application/x-www-form-urlencoded")
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req3})
-	assert.True(t, ok)
-	assert.Equal(t, nil, usr)
-	require.Error(t, err)
-
-	mpbody := bytes.NewBuffer(nil)
-	writer := multipart.NewWriter(mpbody)
-	require.NoError(t, writer.WriteField("access_token", "token124"))
-	writer.Close()
-	req4, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", mpbody)
-	require.NoError(t, err)
-	req4.Header.Set("Content-Type", writer.FormDataContentType())
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req4})
-	assert.True(t, ok)
-	assert.Equal(t, nil, usr)
-	require.Error(t, err)
+func shouldAuthorizeOrNot(expectAuthorized authExpectation) string {
+	if expectAuthorized == expectIsAuthorized {
+		return "should authorize"
+	}
+
+	return "should not authorize"
 }
 
-//nolint:dupl
-func TestMissingBearerAuth(t *testing.T) {
-	ba := BearerAuth("owners_auth", bearerAuth)
-
-	req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?access_toke=token123", nil)
-	require.NoError(t, err)
-
-	ok, usr, err := ba.Authenticate(&ScopedAuthRequest{Request: req1})
-	assert.False(t, ok)
-	assert.Equal(t, nil, usr)
-	require.NoError(t, err)
-
-	req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil)
-	require.NoError(t, err)
-	req2.Header.Set(runtime.HeaderAuthorization, "Beare token123")
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2})
-	assert.False(t, ok)
-	assert.Equal(t, nil, usr)
-	require.NoError(t, err)
-
-	body := url.Values(map[string][]string{})
-	body.Set("access_toke", "token123")
-	req3, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", strings.NewReader(body.Encode()))
-	require.NoError(t, err)
-	req3.Header.Set("Content-Type", "application/x-www-form-urlencoded")
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req3})
-	assert.False(t, ok)
-	assert.Equal(t, nil, usr)
-	require.NoError(t, err)
-
-	mpbody := bytes.NewBuffer(nil)
-	writer := multipart.NewWriter(mpbody)
-	require.NoError(t, writer.WriteField("access_toke", "token123"))
-	writer.Close()
-	req4, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", mpbody)
-	require.NoError(t, err)
-	req4.Header.Set("Content-Type", writer.FormDataContentType())
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req4})
-	assert.False(t, ok)
-	assert.Equal(t, nil, usr)
-	require.NoError(t, err)
+func testAuthenticateBearerInQuery(
+	// build a request with the token as a query parameter, then check against the authorizer
+	//
+	// the request context after authorization may be checked with the extraAsserters.
+	ctx context.Context, authorizer runtime.Authenticator, parameter, token string, expectAuthorized authExpectation,
+	extraAsserters ...func(context.Context, *testing.T),
+) func(*testing.T) {
+	if parameter == "" {
+		parameter = accessTokenParam
+	}
+
+	return func(t *testing.T) {
+		req, err := http.NewRequestWithContext(
+			ctx, http.MethodGet,
+			fmt.Sprintf("%s?%s=%s", authPath, parameter, token),
+			nil,
+		)
+		require.NoError(t, err)
+
+		t.Run(
+			shouldAuthorizeOrNot(expectAuthorized),
+			testIsAuthorized(ctx, req, authorizer, expectAuthorized, extraAsserters...),
+		)
+	}
 }
 
-var bearerAuthCtx = ScopedTokenAuthenticationCtx(func(ctx context.Context, token string, requiredScopes []string) (context.Context, interface{}, error) {
-	if token == "token123" {
-		return context.WithValue(ctx, extra, extraWisdom), "admin", nil
+func testAuthenticateBearerInHeader(
+	// build a request with the token as a header, then check against the authorizer
+	ctx context.Context, authorizer runtime.Authenticator, parameter, token string, expectAuthorized authExpectation,
+	extraAsserters ...func(context.Context, *testing.T),
+) func(*testing.T) {
+	if parameter == "" {
+		parameter = "Bearer"
+	}
+
+	return func(t *testing.T) {
+		req, err := http.NewRequestWithContext(ctx, http.MethodGet, authPath, nil)
+		require.NoError(t, err)
+		req.Header.Set(runtime.HeaderAuthorization, fmt.Sprintf("%s %s", parameter, token))
+
+		t.Run(
+			shouldAuthorizeOrNot(expectAuthorized),
+			testIsAuthorized(ctx, req, authorizer, expectAuthorized, extraAsserters...),
+		)
 	}
-	return context.WithValue(ctx, reason, expReason), nil, errors.Unauthenticated("bearer")
-})
-
-func TestValidBearerAuthCtx(t *testing.T) {
-	ba := BearerAuthCtx("owners_auth", bearerAuthCtx)
-
-	req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?access_token=token123", nil)
-	require.NoError(t, err)
-	req1 = req1.WithContext(context.WithValue(req1.Context(), original, wisdom))
-	ok, usr, err := ba.Authenticate(&ScopedAuthRequest{Request: req1})
-	assert.True(t, ok)
-	assert.Equal(t, "admin", usr)
-	require.NoError(t, err)
-	assert.Equal(t, wisdom, req1.Context().Value(original))
-	assert.Equal(t, extraWisdom, req1.Context().Value(extra))
-	assert.Nil(t, req1.Context().Value(reason))
-	assert.Equal(t, "owners_auth", OAuth2SchemeName(req1))
-
-	req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil)
-	require.NoError(t, err)
-	req2 = req2.WithContext(context.WithValue(req2.Context(), original, wisdom))
-	req2.Header.Set(runtime.HeaderAuthorization, "Bearer token123")
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2})
-	assert.True(t, ok)
-	assert.Equal(t, "admin", usr)
-	require.NoError(t, err)
-	assert.Equal(t, wisdom, req2.Context().Value(original))
-	assert.Equal(t, extraWisdom, req2.Context().Value(extra))
-	assert.Nil(t, req2.Context().Value(reason))
-	assert.Equal(t, "owners_auth", OAuth2SchemeName(req2))
-
-	body := url.Values(map[string][]string{})
-	body.Set("access_token", "token123")
-	req3, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", strings.NewReader(body.Encode()))
-	require.NoError(t, err)
-	req3 = req3.WithContext(context.WithValue(req3.Context(), original, wisdom))
-	req3.Header.Set("Content-Type", "application/x-www-form-urlencoded")
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req3})
-	assert.True(t, ok)
-	assert.Equal(t, "admin", usr)
-	require.NoError(t, err)
-	assert.Equal(t, wisdom, req3.Context().Value(original))
-	assert.Equal(t, extraWisdom, req3.Context().Value(extra))
-	assert.Nil(t, req3.Context().Value(reason))
-	assert.Equal(t, "owners_auth", OAuth2SchemeName(req3))
-
-	mpbody := bytes.NewBuffer(nil)
-	writer := multipart.NewWriter(mpbody)
-	require.NoError(t, writer.WriteField("access_token", "token123"))
-	writer.Close()
-	req4, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", mpbody)
-	require.NoError(t, err)
-	req4 = req4.WithContext(context.WithValue(req4.Context(), original, wisdom))
-	req4.Header.Set("Content-Type", writer.FormDataContentType())
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req4})
-	assert.True(t, ok)
-	assert.Equal(t, "admin", usr)
-	require.NoError(t, err)
-	assert.Equal(t, wisdom, req4.Context().Value(original))
-	assert.Equal(t, extraWisdom, req4.Context().Value(extra))
-	assert.Nil(t, req4.Context().Value(reason))
-	assert.Equal(t, "owners_auth", OAuth2SchemeName(req4))
 }
 
-func TestInvalidBearerAuthCtx(t *testing.T) {
-	ba := BearerAuthCtx("owners_auth", bearerAuthCtx)
-
-	req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?access_token=token124", nil)
-	require.NoError(t, err)
-	req1 = req1.WithContext(context.WithValue(req1.Context(), original, wisdom))
-	ok, usr, err := ba.Authenticate(&ScopedAuthRequest{Request: req1})
-	assert.True(t, ok)
-	assert.Equal(t, nil, usr)
-	require.Error(t, err)
-	assert.Equal(t, wisdom, req1.Context().Value(original))
-	assert.Equal(t, expReason, req1.Context().Value(reason))
-	assert.Nil(t, req1.Context().Value(extra))
-
-	req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil)
-	require.NoError(t, err)
-	req2 = req2.WithContext(context.WithValue(req2.Context(), original, wisdom))
-	req2.Header.Set(runtime.HeaderAuthorization, "Bearer token124")
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2})
-	assert.True(t, ok)
-	assert.Equal(t, nil, usr)
-	require.Error(t, err)
-	assert.Equal(t, wisdom, req2.Context().Value(original))
-	assert.Equal(t, expReason, req2.Context().Value(reason))
-	assert.Nil(t, req2.Context().Value(extra))
-
-	body := url.Values(map[string][]string{})
-	body.Set("access_token", "token124")
-	req3, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", strings.NewReader(body.Encode()))
-	require.NoError(t, err)
-	req3 = req3.WithContext(context.WithValue(req3.Context(), original, wisdom))
-	req3.Header.Set("Content-Type", "application/x-www-form-urlencoded")
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req3})
-	assert.True(t, ok)
-	assert.Equal(t, nil, usr)
-	require.Error(t, err)
-	assert.Equal(t, wisdom, req3.Context().Value(original))
-	assert.Equal(t, expReason, req3.Context().Value(reason))
-	assert.Nil(t, req3.Context().Value(extra))
-
-	mpbody := bytes.NewBuffer(nil)
-	writer := multipart.NewWriter(mpbody)
-	require.NoError(t, writer.WriteField("access_token", "token124"))
-	writer.Close()
-	req4, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", mpbody)
-	require.NoError(t, err)
-	req4 = req4.WithContext(context.WithValue(req4.Context(), original, wisdom))
-	req4.Header.Set("Content-Type", writer.FormDataContentType())
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req4})
-	assert.True(t, ok)
-	assert.Equal(t, nil, usr)
-	require.Error(t, err)
-	assert.Equal(t, wisdom, req4.Context().Value(original))
-	assert.Equal(t, expReason, req4.Context().Value(reason))
-	assert.Nil(t, req4.Context().Value(extra))
+func testAuthenticateBearerInForm(
+	// build a request with the token as a form field, then check against the authorizer
+	ctx context.Context, authorizer runtime.Authenticator, parameter, token string, expectAuthorized authExpectation,
+	extraAsserters ...func(context.Context, *testing.T),
+) func(*testing.T) {
+	if parameter == "" {
+		parameter = accessTokenParam
+	}
+
+	return func(t *testing.T) {
+		body := url.Values(map[string][]string{})
+		body.Set(parameter, token)
+		req, err := http.NewRequestWithContext(ctx, http.MethodPost, authPath, strings.NewReader(body.Encode()))
+		require.NoError(t, err)
+		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+
+		t.Run(
+			shouldAuthorizeOrNot(expectAuthorized),
+			testIsAuthorized(ctx, req, authorizer, expectAuthorized, extraAsserters...),
+		)
+	}
 }
+func testAuthenticateBearerInMultipartForm(
+	// build a request with the token as a multipart form field, then check against the authorizer
+	ctx context.Context, authorizer runtime.Authenticator, parameter, token string, expectAuthorized authExpectation,
+	extraAsserters ...func(context.Context, *testing.T),
+) func(*testing.T) {
+	if parameter == "" {
+		parameter = accessTokenParam
+	}
 
-func TestMissingBearerAuthCtx(t *testing.T) {
-	ba := BearerAuthCtx("owners_auth", bearerAuthCtx)
-
-	req1, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah?access_toke=token123", nil)
-	require.NoError(t, err)
-	req1 = req1.WithContext(context.WithValue(req1.Context(), original, wisdom))
-	ok, usr, err := ba.Authenticate(&ScopedAuthRequest{Request: req1})
-	assert.False(t, ok)
-	assert.Equal(t, nil, usr)
-	require.NoError(t, err)
-	assert.Equal(t, wisdom, req1.Context().Value(original))
-	assert.Nil(t, req1.Context().Value(reason))
-	assert.Nil(t, req1.Context().Value(extra))
-
-	req2, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/blah", nil)
-	require.NoError(t, err)
-	req2.Header.Set(runtime.HeaderAuthorization, "Beare token123")
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req2})
-	req2 = req2.WithContext(context.WithValue(req2.Context(), original, wisdom))
-	assert.False(t, ok)
-	assert.Equal(t, nil, usr)
-	require.NoError(t, err)
-	assert.Equal(t, wisdom, req2.Context().Value(original))
-	assert.Nil(t, req2.Context().Value(reason))
-	assert.Nil(t, req2.Context().Value(extra))
-
-	body := url.Values(map[string][]string{})
-	body.Set("access_toke", "token123")
-	req3, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", strings.NewReader(body.Encode()))
-	require.NoError(t, err)
-	req3 = req3.WithContext(context.WithValue(req3.Context(), original, wisdom))
-	req3.Header.Set("Content-Type", "application/x-www-form-urlencoded")
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req3})
-	assert.False(t, ok)
-	assert.Equal(t, nil, usr)
-	require.NoError(t, err)
-	assert.Equal(t, wisdom, req3.Context().Value(original))
-	assert.Nil(t, req3.Context().Value(reason))
-	assert.Nil(t, req3.Context().Value(extra))
-
-	mpbody := bytes.NewBuffer(nil)
-	writer := multipart.NewWriter(mpbody)
-	err = writer.WriteField("access_toke", "token123")
-	require.NoError(t, err)
-	require.NoError(t, writer.Close())
-	req4, err := http.NewRequestWithContext(context.Background(), http.MethodPost, "/blah", mpbody)
-	require.NoError(t, err)
-	req4 = req4.WithContext(context.WithValue(req4.Context(), original, wisdom))
-	req4.Header.Set("Content-Type", writer.FormDataContentType())
-
-	ok, usr, err = ba.Authenticate(&ScopedAuthRequest{Request: req4})
-	assert.False(t, ok)
-	assert.Equal(t, nil, usr)
-	require.NoError(t, err)
-	assert.Equal(t, wisdom, req4.Context().Value(original))
-	assert.Nil(t, req4.Context().Value(reason))
-	assert.Nil(t, req4.Context().Value(extra))
+	return func(t *testing.T) {
+		body := bytes.NewBuffer(nil)
+		writer := multipart.NewWriter(body)
+		require.NoError(t, writer.WriteField(parameter, token))
+		require.NoError(t, writer.Close())
+		req, err := http.NewRequestWithContext(ctx, http.MethodPost, authPath, body)
+		require.NoError(t, err)
+		req.Header.Set("Content-Type", writer.FormDataContentType())
+
+		t.Run(
+			shouldAuthorizeOrNot(expectAuthorized),
+			testIsAuthorized(ctx, req, authorizer, expectAuthorized, extraAsserters...),
+		)
+	}
 }