Skip to content

Middleware for securitySchemes? #114

Closed

Description

@tboerger

Thanks for this great project, currently I'm replacing go-swagger by this project based on the chi templates.

Most, but not all of my API endpoints require an authentication based on basic auth, bearer token or an header token, how can this get generated? I think the endpoints that require authentication should add a middleware which calls a configured callback function.

I can't see a way how to properly do that from outside of the code, do I really need to add these checks to every handler manually?

Are you open to some generated middleware instead? For go-swagger I had definitions similar to this, which had been invoked automatically:


	api.HeaderAuth = func(ctx context.Context, val string) (context.Context, *models.User, error) {
		t, err := token.Parse(val, cfg.Session.Secret)

		if err != nil {
			return ctx, nil, errors.New(401, "incorrect auth")
		}

		user, err := users.Show(ctx, t.Text)

		if err != nil {
			return ctx, nil, errors.New(401, "incorrect auth")
		}

		return ctx, convertUser(user), nil
	}

	api.BasicAuth = func(ctx context.Context, username, password string) (context.Context, *models.User, error) {
		user, err := users.ByBasicAuth(ctx, username, password)

		if err != nil {
			return ctx, nil, errors.New(401, "incorrect auth")
		}

		return ctx, convertUser(user), nil
	}

Activity

  1. tboerger commented on Jan 8, 2020

    @tboerger
    ContributorAuthor

    I think #118 could be a solution because I can simply check within a middleware if one of the scopes is given.

  2. tboerger commented on Jan 8, 2020

    @tboerger
    ContributorAuthor

    My pr won't resolve that as I can't inject a middleware between context and handler :(

  3. jotdl commented on Jan 27, 2020

    @jotdl

    Hey, We are currently facing the same issue. We don't want to manually add a security validation to each method in the server interface and instead use a global security verification. We came up with an 2 step based approach:

    1. We added a callback to the ServerInterfaceWrapper struct to contain a
    secure func(ctx echo.Context, provider string, scopes []string) error
    

    field, which is then called by each operation for each security (if this field is set), right before the actual domain method is called. If secure returns an error the actual handler is never called.

    1. We extended the RegisterHandlers method to take a variable amount of option functions which can be used to modify the ServerInterfaceWrapper. For now we would just generated a WithSecurity HandlerOption to set the secure field used in step 1. This way the RegisterHandlers method would stay backwards compatible but can be easily extended in the future. The generate code looks something like this:
    type HandlerOption func(wrapper *ServerInterfaceWrapper)
    
    func RegisterHandlers(router ..., si ServerInterface, options ...HandlerOption) {
        wrapper := ServerInterfaceWrapper{
            Handler: si,
        }
        for _, opt := range options {
            opt(&wrapper)
        }
        ... 
    }
    
    func WithSecurity(guard func(ctx echo.Context, provider string, _ []string) error) HandlerOption {
    	return func(wrapper *ServerInterfaceWrapper) {
    		wrapper.secure = guard
    	}
    }
    

    All the required modifications are already done (see https://github.com/jotdl/oapi-codegen/tree/feature/central-security ), I would just need to polish it, add some tests and open the PR.

    What do you think about this solution? Does that sound like a useful solution to this problem? Is there interest for this solution in general?

    I would be happy about any feedback and change request!

    Thanks for your feedback!

  4. utx0 commented on Apr 28, 2020

    @utx0

    Hey guys,

    I am also looking into the problem right now. Am wondering @jotdl how did you go with that PR at all? Be also really great to see a demo implementation of this too. As for me, this is taking some research to work out how to apply securitySchemes into my API.

    Anyway, let me know how I can help get this over the line.

  5. jotdl commented on Apr 28, 2020

    @jotdl

    Hi,

    @lukekhamilton As I didn't get any feedback to the proposed change in this thread, the change is still on hold. But actually I iterated on this last week and came to a solution which doesn't require any changes to oapi-codegen at all, while still reducing maintenance effort to a minimum by relying on code generation:

    As you probably know oapi-codegen generates a ServerInterface interface which contains one method for each of your endpoints. By using composition we could generate a wrapper for this interface which wraps each secured method and verifies security. This would look something like:

    // SecurityMiddleware authenticates incoming requests against the specified provider
    type SecurityMiddleware func(ctx echo.Context, provider string, scopes []string) error
    
    // secureServer is a small wrapper around an ServerInterface to ensure security through a centralised security middleware
    type secureServer struct {
    	ServerInterface
    
    	secure SecurityMiddleware
    }
    
    func NewSecureServer(srv ServerInterface, securityLayer SecurityMiddleware) ServerInterface {
    	return &secureServer{
    		ServerInterface: srv,
    		secure:          securityLayer,
    	}
    }

    For methods/endpoints which need to be secured, we could go with something like this:

    // (POST /api)
    func (s *secureServer) Api(ctx echo.Context) error {
    	if err := s.secure(ctx, "api-key", nil); err != nil {
    		return err
    	}
    	return s.ServerInterface.Api(ctx)
    }

    This way you stay compatible with the oapi-codegen generated API by reusing the ServerInterface interface and initialising a centralised security layer is as easy as:

    srv = NewSecureServer(srv, customSecurityMiddleware)
    RegisterHandlers(api, srv)

    As this doesn't require any changes to oapi-codegen (just a little bit more code on top), we dropped my previously suggested approach and went with this one. Once we completely migrated to this approache I will delete the code changes from my previous approach. But in general I would be happy about any feedback about this approach!

    The same solution for chi-server should look very similar as it's using a ServerInterface interface there, too.

    As oapi-codegen can be easily used as a library, we also generate all of this code in a very lightweight wrapper around oapi-codegen. It just took roughly 100 lines of Go to automate all of this. If you are interested in this I would be happy to share.

    The only thing to make this even easier would be the opportunity to add additional code generation templates (not replacing existing ones) to oapi-codegen. I am not aware that this is already possible, but maybe it's worth considering. But except that, we are really happy with the current oapi-codegen API!

  6. utx0 commented on Apr 28, 2020

    @utx0

    Hey @jotdl, thanks for all the info. I'll be sure to give this approach a try tomorrow.

    I would also very much love to have a look at the wrapper approach you have put together too and see what I can learn/use here too.

    From my understanding of the oapi-codegen codebase I dont think you can add custom/additional code generation templates that are implemented in a project namespace. I know this type of thing exist in the go-swagger approach from memory. Not really sure what it would take to make that possible here tho.

  7. jotdl commented on Apr 30, 2020

    @jotdl

    Hi,
    Excuse my late reply. Please find below a sample version of the wrapper we are currently using for generating the security layer on top of what's already been generated by oapi codegen:

    package main
    
    import (
    	"bytes"
    	"fmt"
    	"github.com/getkin/kin-openapi/openapi3"
    	"go/format"
    	"io/ioutil"
    	"os"
    	"text/template"
    
    	"github.com/deepmap/oapi-codegen/pkg/codegen"
    	"github.com/deepmap/oapi-codegen/pkg/util"
    )
    
    const securityLayerTmpl = `
    // SecurityMiddleware authenticates incoming requests against the specified provider
    type SecurityMiddleware func(ctx echo.Context, provider string, scopes []string) error
    
    // secureServer is a small wrapper around an ServerInterface to ensure security through a centralised security middleware
    type secureServer struct {
    	ServerInterface
    
    	secure SecurityMiddleware
    }
    
    func NewSecureServer(srv ServerInterface, securityLayer SecurityMiddleware) ServerInterface {
    	return &secureServer{
    		ServerInterface: srv,
    		secure:          securityLayer,
    	}
    }
    
    {{range .}}
    {{- if .SecurityDefinitions -}}
    // ({{.Method}} {{.Path}})
    func (s *secureServer) {{.OperationId}}(ctx echo.Context{{genParamArgs .PathParams}}{{if .RequiresParamObject}}, params {{.OperationId}}Params{{end}}) error {
    	{{range .SecurityDefinitions -}}
    	if err := s.secure(ctx, "{{.ProviderName}}", nil); err != nil {
    		return err
    	}
    	{{end -}}
    
    	return s.ServerInterface.{{.OperationId}}(ctx{{genParamNames .PathParams}}{{if .RequiresParamObject}}, params{{end}})
    }
    {{end}}
    {{end}}
    `
    
    func main() {
    	opts := codegen.Options{
    		GenerateEchoServer: true,
    		GenerateTypes:      true,
    		EmbedSpec:          true,
    	}
    
    	swagger, err := util.LoadSwagger("schema.yaml")
    	if err != nil {
    		_, _ = fmt.Fprintf(os.Stderr, "error loading swagger spec\n: %s", err)
    		os.Exit(1)
    	}
    
    	code, err := codegen.Generate(swagger, "main", opts)
    	if err != nil {
    		_, _ = fmt.Fprintf(os.Stderr, "error generating code: %s\n", err)
    		os.Exit(1)
    	}
    
    	rawCode := []byte(code)
    
    	// let's check if we have security defined
    	if len(swagger.Security) > 0 {
    		rawCode = generateSecurityLayer(code, swagger, err, rawCode)
    	}
    
    	err = ioutil.WriteFile("server.gen.go", rawCode, 0644)
    	if err != nil {
    		_, _ = fmt.Fprintf(os.Stderr, "error writing generated code to file: %s", err)
    		os.Exit(1)
    	}
    }
    
    func generateSecurityLayer(code string, swagger *openapi3.Swagger, err error, currentCode []byte) []byte {
    	writer := bytes.Buffer{}
    	writer.WriteString(code)
    
    	ops, _ := codegen.OperationDefinitions(swagger) // err can not occur as this function is also used by codegen.Generate before (and would already fail there)
    
    	tmpl := template.Must(template.New("").Funcs(codegen.TemplateFunctions).Parse(securityLayerTmpl))
    	err = tmpl.Execute(&writer, ops)
    	if err != nil {
    		_, _ = fmt.Fprintf(os.Stderr, "error generating security layer: %s", err)
    		os.Exit(1)
    	}
    
    	bytes, err := format.Source(writer.Bytes())
    	if err != nil {
    		_, _ = fmt.Fprintf(os.Stderr, "error formating generated security layer: %s", err)
    		os.Exit(1)
    	}
    	return bytes
    }

    We currently invoke this with a //go:generate comment similar to this example

    //go:generate go run <pkg>/cmd/generators/server-gen > server.gen.go

    or run directly via

    go run <pkg>/cmd/generators/server-gen > server.gen.go

    This script relies on having the schema.yaml in the same directory where the code generator is executed and also predefines all options passed to oapi-codegen. This fits our usecase as we want to ensure that always the same kind of server is generated. But it might need more options in other use cases.

    Basically all of this is heavily inspired by the templates and code which are already in oapi-codegen and just tries to follow the way oapi-codegen is written. But still its in an early phase and might not be perfect, yet.

    Please let me know if you have any questions. I would be happy to answer them.

  8. utx0 commented on Apr 30, 2020

    @utx0

    Yeah thanks, heaps for that @jotdl. Today I built in my auth stuff following the advice you gave in this comment.

    This has worked to get me over the line with my direct requirement for sure, however, be nice to package this up in this repo.

    I looked at the work you have done here and I quite like this approach.

    I am wondering if @deepmap-marcinr has any input on how he would like the securitySchemes implementation to look for this package? And if this approach is worth finalizing?

  9. utx0 commented on Apr 30, 2020

    @utx0

    One thing that would be nice is to be able to define a middleware that gets applied to the endpoint and then not having to do the following in the actual endpoint implementation;

    func (h *Handlers) GetJWT(ctx echo.Context) error {
    	if err := h.secure(ctx, "", nil); err != nil {
    		return ctx.JSON(http.StatusUnauthorized, "AUTH FAILED")
    	}
           ...
    }
    
    
    
  10. mromaszewicz commented on Jun 18, 2024

    @mromaszewicz
    Member

    Since this bug was filed, we've created middleware to help with security validation, and also provided examples of how to use it.

  11. tboerger commented on Jun 18, 2024

    @tboerger
    ContributorAuthor

    Just the chi middleware is incomplete because it's lacking a working context set and get :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions