docker_cli_authz_unix_test.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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. // start the daemon and load busybox, --net=none build fails otherwise
  139. // cause it needs to pull busybox
  140. c.Assert(s.d.StartWithBusybox(), check.IsNil)
  141. // restart the daemon and enable the plugin, otherwise busybox loading
  142. // is blocked by the plugin itself
  143. c.Assert(s.d.Restart("--authorization-plugin="+testAuthZPlugin), check.IsNil)
  144. s.ctrl.reqRes.Allow = true
  145. s.ctrl.resRes.Allow = true
  146. // Ensure command successful
  147. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  148. c.Assert(err, check.IsNil)
  149. id := strings.TrimSpace(out)
  150. assertURIRecorded(c, s.ctrl.requestsURIs, "/containers/create")
  151. assertURIRecorded(c, s.ctrl.requestsURIs, fmt.Sprintf("/containers/%s/start", id))
  152. out, err = s.d.Cmd("ps")
  153. c.Assert(err, check.IsNil)
  154. c.Assert(assertContainerList(out, []string{id}), check.Equals, true)
  155. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  156. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  157. }
  158. func (s *DockerAuthzSuite) TestAuthZPluginDenyRequest(c *check.C) {
  159. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  160. c.Assert(err, check.IsNil)
  161. s.ctrl.reqRes.Allow = false
  162. s.ctrl.reqRes.Msg = unauthorizedMessage
  163. // Ensure command is blocked
  164. res, err := s.d.Cmd("ps")
  165. c.Assert(err, check.NotNil)
  166. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  167. c.Assert(s.ctrl.psResponseCnt, check.Equals, 0)
  168. // Ensure unauthorized message appears in response
  169. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: authorization denied by plugin %s: %s\n", testAuthZPlugin, unauthorizedMessage))
  170. }
  171. func (s *DockerAuthzSuite) TestAuthZPluginDenyResponse(c *check.C) {
  172. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  173. c.Assert(err, check.IsNil)
  174. s.ctrl.reqRes.Allow = true
  175. s.ctrl.resRes.Allow = false
  176. s.ctrl.resRes.Msg = unauthorizedMessage
  177. // Ensure command is blocked
  178. res, err := s.d.Cmd("ps")
  179. c.Assert(err, check.NotNil)
  180. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  181. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  182. // Ensure unauthorized message appears in response
  183. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: authorization denied by plugin %s: %s\n", testAuthZPlugin, unauthorizedMessage))
  184. }
  185. func (s *DockerAuthzSuite) TestAuthZPluginErrorResponse(c *check.C) {
  186. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  187. c.Assert(err, check.IsNil)
  188. s.ctrl.reqRes.Allow = true
  189. s.ctrl.resRes.Err = errorMessage
  190. // Ensure command is blocked
  191. res, err := s.d.Cmd("ps")
  192. c.Assert(err, check.NotNil)
  193. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s\n", testAuthZPlugin, authorization.AuthZApiResponse, errorMessage))
  194. }
  195. func (s *DockerAuthzSuite) TestAuthZPluginErrorRequest(c *check.C) {
  196. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  197. c.Assert(err, check.IsNil)
  198. s.ctrl.reqRes.Err = errorMessage
  199. // Ensure command is blocked
  200. res, err := s.d.Cmd("ps")
  201. c.Assert(err, check.NotNil)
  202. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s\n", testAuthZPlugin, authorization.AuthZApiRequest, errorMessage))
  203. }
  204. func (s *DockerAuthzSuite) TestAuthZPluginEnsureNoDuplicatePluginRegistration(c *check.C) {
  205. c.Assert(s.d.Start("--authorization-plugin="+testAuthZPlugin, "--authorization-plugin="+testAuthZPlugin), check.IsNil)
  206. s.ctrl.reqRes.Allow = true
  207. s.ctrl.resRes.Allow = true
  208. out, err := s.d.Cmd("ps")
  209. c.Assert(err, check.IsNil, check.Commentf(out))
  210. // assert plugin is only called once..
  211. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  212. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  213. }
  214. // assertURIRecorded verifies that the given URI was sent and recorded in the authz plugin
  215. func assertURIRecorded(c *check.C, uris []string, uri string) {
  216. var found bool
  217. for _, u := range uris {
  218. if strings.Contains(u, uri) {
  219. found = true
  220. break
  221. }
  222. }
  223. if !found {
  224. c.Fatalf("Expected to find URI '%s', recorded uris '%s'", uri, strings.Join(uris, ","))
  225. }
  226. }