docker_cli_authz_unix_test.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. // +build !windows
  2. package main
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "net/http/httptest"
  9. "os"
  10. "strings"
  11. "github.com/docker/docker/pkg/authorization"
  12. "github.com/docker/docker/pkg/integration/checker"
  13. "github.com/docker/docker/pkg/plugins"
  14. "github.com/go-check/check"
  15. )
  16. const (
  17. testAuthZPlugin = "authzplugin"
  18. unauthorizedMessage = "User unauthorized authz plugin"
  19. errorMessage = "something went wrong..."
  20. containerListAPI = "/containers/json"
  21. )
  22. func init() {
  23. check.Suite(&DockerAuthzSuite{
  24. ds: &DockerSuite{},
  25. })
  26. }
  27. type DockerAuthzSuite struct {
  28. server *httptest.Server
  29. ds *DockerSuite
  30. d *Daemon
  31. ctrl *authorizationController
  32. }
  33. type authorizationController struct {
  34. reqRes authorization.Response // reqRes holds the plugin response to the initial client request
  35. resRes authorization.Response // resRes holds the plugin response to the daemon response
  36. psRequestCnt int // psRequestCnt counts the number of calls to list container request api
  37. psResponseCnt int // psResponseCnt counts the number of calls to list containers response API
  38. requestsURIs []string // requestsURIs stores all request URIs that are sent to the authorization controller
  39. }
  40. func (s *DockerAuthzSuite) SetUpTest(c *check.C) {
  41. s.d = NewDaemon(c)
  42. s.ctrl = &authorizationController{}
  43. }
  44. func (s *DockerAuthzSuite) TearDownTest(c *check.C) {
  45. s.d.Stop()
  46. s.ds.TearDownTest(c)
  47. s.ctrl = nil
  48. }
  49. func (s *DockerAuthzSuite) SetUpSuite(c *check.C) {
  50. mux := http.NewServeMux()
  51. s.server = httptest.NewServer(mux)
  52. c.Assert(s.server, check.NotNil, check.Commentf("Failed to start a HTTP Server"))
  53. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  54. b, err := json.Marshal(plugins.Manifest{Implements: []string{authorization.AuthZApiImplements}})
  55. c.Assert(err, check.IsNil)
  56. w.Write(b)
  57. })
  58. mux.HandleFunc("/AuthZPlugin.AuthZReq", func(w http.ResponseWriter, r *http.Request) {
  59. if s.ctrl.reqRes.Err != "" {
  60. w.WriteHeader(http.StatusInternalServerError)
  61. }
  62. b, err := json.Marshal(s.ctrl.reqRes)
  63. c.Assert(err, check.IsNil)
  64. w.Write(b)
  65. defer r.Body.Close()
  66. body, err := ioutil.ReadAll(r.Body)
  67. c.Assert(err, check.IsNil)
  68. authReq := authorization.Request{}
  69. err = json.Unmarshal(body, &authReq)
  70. c.Assert(err, check.IsNil)
  71. assertBody(c, authReq.RequestURI, authReq.RequestHeaders, authReq.RequestBody)
  72. assertAuthHeaders(c, authReq.RequestHeaders)
  73. // Count only container list api
  74. if strings.HasSuffix(authReq.RequestURI, containerListAPI) {
  75. s.ctrl.psRequestCnt++
  76. }
  77. s.ctrl.requestsURIs = append(s.ctrl.requestsURIs, authReq.RequestURI)
  78. })
  79. mux.HandleFunc("/AuthZPlugin.AuthZRes", func(w http.ResponseWriter, r *http.Request) {
  80. if s.ctrl.resRes.Err != "" {
  81. w.WriteHeader(http.StatusInternalServerError)
  82. }
  83. b, err := json.Marshal(s.ctrl.resRes)
  84. c.Assert(err, check.IsNil)
  85. w.Write(b)
  86. defer r.Body.Close()
  87. body, err := ioutil.ReadAll(r.Body)
  88. c.Assert(err, check.IsNil)
  89. authReq := authorization.Request{}
  90. err = json.Unmarshal(body, &authReq)
  91. c.Assert(err, check.IsNil)
  92. assertBody(c, authReq.RequestURI, authReq.ResponseHeaders, authReq.ResponseBody)
  93. assertAuthHeaders(c, authReq.ResponseHeaders)
  94. // Count only container list api
  95. if strings.HasSuffix(authReq.RequestURI, containerListAPI) {
  96. s.ctrl.psResponseCnt++
  97. }
  98. })
  99. err := os.MkdirAll("/etc/docker/plugins", 0755)
  100. c.Assert(err, checker.IsNil)
  101. fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", testAuthZPlugin)
  102. err = ioutil.WriteFile(fileName, []byte(s.server.URL), 0644)
  103. c.Assert(err, checker.IsNil)
  104. }
  105. // assertAuthHeaders validates authentication headers are removed
  106. func assertAuthHeaders(c *check.C, headers map[string]string) error {
  107. for k := range headers {
  108. if strings.Contains(strings.ToLower(k), "auth") || strings.Contains(strings.ToLower(k), "x-registry") {
  109. c.Errorf("Found authentication headers in request '%v'", headers)
  110. }
  111. }
  112. return nil
  113. }
  114. // assertBody asserts that body is removed for non text/json requests
  115. func assertBody(c *check.C, requestURI string, headers map[string]string, body []byte) {
  116. if strings.Contains(strings.ToLower(requestURI), "auth") && len(body) > 0 {
  117. //return fmt.Errorf("Body included for authentication endpoint %s", string(body))
  118. c.Errorf("Body included for authentication endpoint %s", string(body))
  119. }
  120. for k, v := range headers {
  121. if strings.EqualFold(k, "Content-Type") && strings.HasPrefix(v, "text/") || v == "application/json" {
  122. return
  123. }
  124. }
  125. if len(body) > 0 {
  126. c.Errorf("Body included while it should not (Headers: '%v')", headers)
  127. }
  128. }
  129. func (s *DockerAuthzSuite) TearDownSuite(c *check.C) {
  130. if s.server == nil {
  131. return
  132. }
  133. s.server.Close()
  134. err := os.RemoveAll("/etc/docker/plugins")
  135. c.Assert(err, checker.IsNil)
  136. }
  137. func (s *DockerAuthzSuite) TestAuthZPluginAllowRequest(c *check.C) {
  138. err := s.d.Start("--authz-plugin=" + testAuthZPlugin)
  139. c.Assert(err, check.IsNil)
  140. s.ctrl.reqRes.Allow = true
  141. s.ctrl.resRes.Allow = true
  142. // Ensure command successful
  143. out, err := s.d.Cmd("run", "-d", "--name", "container1", "busybox:latest", "top")
  144. c.Assert(err, check.IsNil)
  145. // Extract the id of the created container
  146. res := strings.Split(strings.TrimSpace(out), "\n")
  147. id := res[len(res)-1]
  148. assertURIRecorded(c, s.ctrl.requestsURIs, "/containers/create")
  149. assertURIRecorded(c, s.ctrl.requestsURIs, fmt.Sprintf("/containers/%s/start", id))
  150. out, err = s.d.Cmd("ps")
  151. c.Assert(err, check.IsNil)
  152. c.Assert(assertContainerList(out, []string{id}), check.Equals, true)
  153. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  154. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  155. }
  156. func (s *DockerAuthzSuite) TestAuthZPluginDenyRequest(c *check.C) {
  157. err := s.d.Start("--authz-plugin=" + testAuthZPlugin)
  158. c.Assert(err, check.IsNil)
  159. s.ctrl.reqRes.Allow = false
  160. s.ctrl.reqRes.Msg = unauthorizedMessage
  161. // Ensure command is blocked
  162. res, err := s.d.Cmd("ps")
  163. c.Assert(err, check.NotNil)
  164. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  165. c.Assert(s.ctrl.psResponseCnt, check.Equals, 0)
  166. // Ensure unauthorized message appears in response
  167. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: authorization denied by plugin %s: %s\n", testAuthZPlugin, unauthorizedMessage))
  168. }
  169. func (s *DockerAuthzSuite) TestAuthZPluginDenyResponse(c *check.C) {
  170. err := s.d.Start("--authz-plugin=" + testAuthZPlugin)
  171. c.Assert(err, check.IsNil)
  172. s.ctrl.reqRes.Allow = true
  173. s.ctrl.resRes.Allow = false
  174. s.ctrl.resRes.Msg = unauthorizedMessage
  175. // Ensure command is blocked
  176. res, err := s.d.Cmd("ps")
  177. c.Assert(err, check.NotNil)
  178. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  179. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  180. // Ensure unauthorized message appears in response
  181. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: authorization denied by plugin %s: %s\n", testAuthZPlugin, unauthorizedMessage))
  182. }
  183. func (s *DockerAuthzSuite) TestAuthZPluginErrorResponse(c *check.C) {
  184. err := s.d.Start("--authz-plugin=" + testAuthZPlugin)
  185. c.Assert(err, check.IsNil)
  186. s.ctrl.reqRes.Allow = true
  187. s.ctrl.resRes.Err = errorMessage
  188. // Ensure command is blocked
  189. res, err := s.d.Cmd("ps")
  190. c.Assert(err, check.NotNil)
  191. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s\n", testAuthZPlugin, authorization.AuthZApiResponse, errorMessage))
  192. }
  193. func (s *DockerAuthzSuite) TestAuthZPluginErrorRequest(c *check.C) {
  194. err := s.d.Start("--authz-plugin=" + testAuthZPlugin)
  195. c.Assert(err, check.IsNil)
  196. s.ctrl.reqRes.Err = errorMessage
  197. // Ensure command is blocked
  198. res, err := s.d.Cmd("ps")
  199. c.Assert(err, check.NotNil)
  200. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s\n", testAuthZPlugin, authorization.AuthZApiRequest, errorMessage))
  201. }
  202. // assertURIRecorded verifies that the given URI was sent and recorded in the authz plugin
  203. func assertURIRecorded(c *check.C, uris []string, uri string) {
  204. found := false
  205. for _, u := range uris {
  206. if strings.Contains(u, uri) {
  207. found = true
  208. }
  209. }
  210. if !found {
  211. c.Fatalf("Expected to find URI '%s', recorded uris '%s'", uri, strings.Join(uris, ","))
  212. }
  213. }