middleware.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. package server
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io/ioutil"
  6. "net/http"
  7. "runtime"
  8. "strings"
  9. "github.com/Sirupsen/logrus"
  10. "github.com/docker/docker/api"
  11. "github.com/docker/docker/api/server/httputils"
  12. "github.com/docker/docker/dockerversion"
  13. "github.com/docker/docker/errors"
  14. "github.com/docker/docker/pkg/authorization"
  15. "github.com/docker/docker/pkg/version"
  16. "golang.org/x/net/context"
  17. )
  18. // middleware is an adapter to allow the use of ordinary functions as Docker API filters.
  19. // Any function that has the appropriate signature can be register as a middleware.
  20. type middleware func(handler httputils.APIFunc) httputils.APIFunc
  21. // debugRequestMiddleware dumps the request to logger
  22. func debugRequestMiddleware(handler httputils.APIFunc) httputils.APIFunc {
  23. return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  24. logrus.Debugf("%s %s", r.Method, r.RequestURI)
  25. if r.Method == "POST" {
  26. if err := httputils.CheckForJSON(r); err == nil {
  27. var buf bytes.Buffer
  28. if _, err := buf.ReadFrom(r.Body); err == nil {
  29. r.Body.Close()
  30. r.Body = ioutil.NopCloser(&buf)
  31. var postForm map[string]interface{}
  32. if err := json.Unmarshal(buf.Bytes(), &postForm); err == nil {
  33. if _, exists := postForm["password"]; exists {
  34. postForm["password"] = "*****"
  35. }
  36. formStr, errMarshal := json.Marshal(postForm)
  37. if errMarshal == nil {
  38. logrus.Debugf("form data: %s", string(formStr))
  39. } else {
  40. logrus.Debugf("form data: %q", postForm)
  41. }
  42. }
  43. }
  44. }
  45. }
  46. return handler(ctx, w, r, vars)
  47. }
  48. }
  49. // authorizationMiddleware perform authorization on the request.
  50. func (s *Server) authorizationMiddleware(handler httputils.APIFunc) httputils.APIFunc {
  51. return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  52. // User and UserAuthNMethod are taken from AuthN plugins
  53. // Currently tracked in https://github.com/docker/docker/pull/13994
  54. user := ""
  55. userAuthNMethod := ""
  56. authCtx := authorization.NewCtx(s.authZPlugins, user, userAuthNMethod, r.Method, r.RequestURI)
  57. if err := authCtx.AuthZRequest(w, r); err != nil {
  58. logrus.Errorf("AuthZRequest for %s %s returned error: %s", r.Method, r.RequestURI, err)
  59. return err
  60. }
  61. rw := authorization.NewResponseModifier(w)
  62. if err := handler(ctx, rw, r, vars); err != nil {
  63. logrus.Errorf("Handler for %s %s returned error: %s", r.Method, r.RequestURI, err)
  64. return err
  65. }
  66. if err := authCtx.AuthZResponse(rw, r); err != nil {
  67. logrus.Errorf("AuthZResponse for %s %s returned error: %s", r.Method, r.RequestURI, err)
  68. return err
  69. }
  70. return nil
  71. }
  72. }
  73. // userAgentMiddleware checks the User-Agent header looking for a valid docker client spec.
  74. func (s *Server) userAgentMiddleware(handler httputils.APIFunc) httputils.APIFunc {
  75. return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  76. if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
  77. dockerVersion := version.Version(s.cfg.Version)
  78. userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
  79. // v1.20 onwards includes the GOOS of the client after the version
  80. // such as Docker/1.7.0 (linux)
  81. if len(userAgent) == 2 && strings.Contains(userAgent[1], " ") {
  82. userAgent[1] = strings.Split(userAgent[1], " ")[0]
  83. }
  84. if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) {
  85. logrus.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
  86. }
  87. }
  88. return handler(ctx, w, r, vars)
  89. }
  90. }
  91. // corsMiddleware sets the CORS header expectations in the server.
  92. func (s *Server) corsMiddleware(handler httputils.APIFunc) httputils.APIFunc {
  93. return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  94. // If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
  95. // otherwise, all head values will be passed to HTTP handler
  96. corsHeaders := s.cfg.CorsHeaders
  97. if corsHeaders == "" && s.cfg.EnableCors {
  98. corsHeaders = "*"
  99. }
  100. if corsHeaders != "" {
  101. writeCorsHeaders(w, r, corsHeaders)
  102. }
  103. return handler(ctx, w, r, vars)
  104. }
  105. }
  106. // versionMiddleware checks the api version requirements before passing the request to the server handler.
  107. func versionMiddleware(handler httputils.APIFunc) httputils.APIFunc {
  108. return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  109. apiVersion := version.Version(vars["version"])
  110. if apiVersion == "" {
  111. apiVersion = api.DefaultVersion
  112. }
  113. if apiVersion.GreaterThan(api.DefaultVersion) {
  114. return errors.ErrorCodeNewerClientVersion.WithArgs(apiVersion, api.DefaultVersion)
  115. }
  116. if apiVersion.LessThan(api.MinVersion) {
  117. return errors.ErrorCodeOldClientVersion.WithArgs(apiVersion, api.DefaultVersion)
  118. }
  119. w.Header().Set("Server", "Docker/"+dockerversion.Version+" ("+runtime.GOOS+")")
  120. ctx = context.WithValue(ctx, httputils.APIVersionKey, apiVersion)
  121. return handler(ctx, w, r, vars)
  122. }
  123. }
  124. // handleWithGlobalMiddlwares wraps the handler function for a request with
  125. // the server's global middlewares. The order of the middlewares is backwards,
  126. // meaning that the first in the list will be evaluated last.
  127. //
  128. // Example: handleWithGlobalMiddlewares(s.getContainersName)
  129. //
  130. // s.loggingMiddleware(
  131. // s.userAgentMiddleware(
  132. // s.corsMiddleware(
  133. // versionMiddleware(s.getContainersName)
  134. // )
  135. // )
  136. // )
  137. // )
  138. func (s *Server) handleWithGlobalMiddlewares(handler httputils.APIFunc) httputils.APIFunc {
  139. middlewares := []middleware{
  140. versionMiddleware,
  141. s.corsMiddleware,
  142. s.userAgentMiddleware,
  143. }
  144. // Only want this on debug level
  145. if s.cfg.Logging && logrus.GetLevel() == logrus.DebugLevel {
  146. middlewares = append(middlewares, debugRequestMiddleware)
  147. }
  148. if len(s.cfg.AuthZPluginNames) > 0 {
  149. s.authZPlugins = authorization.NewPlugins(s.cfg.AuthZPluginNames)
  150. middlewares = append(middlewares, s.authorizationMiddleware)
  151. }
  152. h := handler
  153. for _, m := range middlewares {
  154. h = m(h)
  155. }
  156. return h
  157. }