github.com/kobeld/docker@v1.12.0-rc1/pkg/authorization/middleware.go (about)

     1  package authorization
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/Sirupsen/logrus"
     7  	"golang.org/x/net/context"
     8  )
     9  
    10  // Middleware uses a list of plugins to
    11  // handle authorization in the API requests.
    12  type Middleware struct {
    13  	plugins []Plugin
    14  }
    15  
    16  // NewMiddleware creates a new Middleware
    17  // with a slice of plugins.
    18  func NewMiddleware(p []Plugin) Middleware {
    19  	return Middleware{
    20  		plugins: p,
    21  	}
    22  }
    23  
    24  // WrapHandler returns a new handler function wrapping the previous one in the request chain.
    25  func (m Middleware) WrapHandler(handler func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error) func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
    26  	return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
    27  
    28  		user := ""
    29  		userAuthNMethod := ""
    30  
    31  		// Default authorization using existing TLS connection credentials
    32  		// FIXME: Non trivial authorization mechanisms (such as advanced certificate validations, kerberos support
    33  		// and ldap) will be extracted using AuthN feature, which is tracked under:
    34  		// https://github.com/docker/docker/pull/20883
    35  		if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 {
    36  			user = r.TLS.PeerCertificates[0].Subject.CommonName
    37  			userAuthNMethod = "TLS"
    38  		}
    39  
    40  		authCtx := NewCtx(m.plugins, user, userAuthNMethod, r.Method, r.RequestURI)
    41  
    42  		if err := authCtx.AuthZRequest(w, r); err != nil {
    43  			logrus.Errorf("AuthZRequest for %s %s returned error: %s", r.Method, r.RequestURI, err)
    44  			return err
    45  		}
    46  
    47  		rw := NewResponseModifier(w)
    48  
    49  		if err := handler(ctx, rw, r, vars); err != nil {
    50  			logrus.Errorf("Handler for %s %s returned error: %s", r.Method, r.RequestURI, err)
    51  			return err
    52  		}
    53  
    54  		if err := authCtx.AuthZResponse(rw, r); err != nil {
    55  			logrus.Errorf("AuthZResponse for %s %s returned error: %s", r.Method, r.RequestURI, err)
    56  			return err
    57  		}
    58  		return nil
    59  	}
    60  }