middleware.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. logrus.Debugf("form data: %q", postForm)
  37. }
  38. }
  39. }
  40. }
  41. return handler(ctx, w, r, vars)
  42. }
  43. }
  44. // authorizationMiddleware perform authorization on the request.
  45. func (s *Server) authorizationMiddleware(handler httputils.APIFunc) httputils.APIFunc {
  46. return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  47. // User and UserAuthNMethod are taken from AuthN plugins
  48. // Currently tracked in https://github.com/docker/docker/pull/13994
  49. user := ""
  50. userAuthNMethod := ""
  51. authCtx := authorization.NewCtx(s.authZPlugins, user, userAuthNMethod, r.Method, r.RequestURI)
  52. if err := authCtx.AuthZRequest(w, r); err != nil {
  53. logrus.Errorf("AuthZRequest for %s %s returned error: %s", r.Method, r.RequestURI, err)
  54. return err
  55. }
  56. rw := authorization.NewResponseModifier(w)
  57. if err := handler(ctx, rw, r, vars); err != nil {
  58. logrus.Errorf("Handler for %s %s returned error: %s", r.Method, r.RequestURI, err)
  59. return err
  60. }
  61. if err := authCtx.AuthZResponse(rw, r); err != nil {
  62. logrus.Errorf("AuthZResponse for %s %s returned error: %s", r.Method, r.RequestURI, err)
  63. return err
  64. }
  65. return nil
  66. }
  67. }
  68. // userAgentMiddleware checks the User-Agent header looking for a valid docker client spec.
  69. func (s *Server) userAgentMiddleware(handler httputils.APIFunc) httputils.APIFunc {
  70. return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  71. if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
  72. dockerVersion := version.Version(s.cfg.Version)
  73. userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
  74. // v1.20 onwards includes the GOOS of the client after the version
  75. // such as Docker/1.7.0 (linux)
  76. if len(userAgent) == 2 && strings.Contains(userAgent[1], " ") {
  77. userAgent[1] = strings.Split(userAgent[1], " ")[0]
  78. }
  79. if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) {
  80. logrus.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
  81. }
  82. }
  83. return handler(ctx, w, r, vars)
  84. }
  85. }
  86. // corsMiddleware sets the CORS header expectations in the server.
  87. func (s *Server) corsMiddleware(handler httputils.APIFunc) httputils.APIFunc {
  88. return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  89. // If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*"
  90. // otherwise, all head values will be passed to HTTP handler
  91. corsHeaders := s.cfg.CorsHeaders
  92. if corsHeaders == "" && s.cfg.EnableCors {
  93. corsHeaders = "*"
  94. }
  95. if corsHeaders != "" {
  96. writeCorsHeaders(w, r, corsHeaders)
  97. }
  98. return handler(ctx, w, r, vars)
  99. }
  100. }
  101. // versionMiddleware checks the api version requirements before passing the request to the server handler.
  102. func versionMiddleware(handler httputils.APIFunc) httputils.APIFunc {
  103. return func(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  104. apiVersion := version.Version(vars["version"])
  105. if apiVersion == "" {
  106. apiVersion = api.DefaultVersion
  107. }
  108. if apiVersion.GreaterThan(api.DefaultVersion) {
  109. return errors.ErrorCodeNewerClientVersion.WithArgs(apiVersion, api.DefaultVersion)
  110. }
  111. if apiVersion.LessThan(api.MinVersion) {
  112. return errors.ErrorCodeOldClientVersion.WithArgs(apiVersion, api.DefaultVersion)
  113. }
  114. w.Header().Set("Server", "Docker/"+dockerversion.Version+" ("+runtime.GOOS+")")
  115. ctx = context.WithValue(ctx, httputils.APIVersionKey, apiVersion)
  116. return handler(ctx, w, r, vars)
  117. }
  118. }
  119. // handleWithGlobalMiddlwares wraps the handler function for a request with
  120. // the server's global middlewares. The order of the middlewares is backwards,
  121. // meaning that the first in the list will be evaluated last.
  122. //
  123. // Example: handleWithGlobalMiddlewares(s.getContainersName)
  124. //
  125. // s.loggingMiddleware(
  126. // s.userAgentMiddleware(
  127. // s.corsMiddleware(
  128. // versionMiddleware(s.getContainersName)
  129. // )
  130. // )
  131. // )
  132. // )
  133. func (s *Server) handleWithGlobalMiddlewares(handler httputils.APIFunc) httputils.APIFunc {
  134. middlewares := []middleware{
  135. versionMiddleware,
  136. s.corsMiddleware,
  137. s.userAgentMiddleware,
  138. }
  139. // Only want this on debug level
  140. if s.cfg.Logging && logrus.GetLevel() == logrus.DebugLevel {
  141. middlewares = append(middlewares, debugRequestMiddleware)
  142. }
  143. if len(s.cfg.AuthZPluginNames) > 0 {
  144. s.authZPlugins = authorization.NewPlugins(s.cfg.AuthZPluginNames)
  145. middlewares = append(middlewares, s.authorizationMiddleware)
  146. }
  147. h := handler
  148. for _, m := range middlewares {
  149. h = m(h)
  150. }
  151. return h
  152. }