docker_cli_authz_unix_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. "bufio"
  12. "bytes"
  13. "github.com/docker/docker/pkg/authorization"
  14. "github.com/docker/docker/pkg/integration/checker"
  15. "github.com/docker/docker/pkg/plugins"
  16. "github.com/go-check/check"
  17. "os/exec"
  18. "strconv"
  19. "time"
  20. )
  21. const (
  22. testAuthZPlugin = "authzplugin"
  23. unauthorizedMessage = "User unauthorized authz plugin"
  24. errorMessage = "something went wrong..."
  25. containerListAPI = "/containers/json"
  26. )
  27. func init() {
  28. check.Suite(&DockerAuthzSuite{
  29. ds: &DockerSuite{},
  30. })
  31. }
  32. type DockerAuthzSuite struct {
  33. server *httptest.Server
  34. ds *DockerSuite
  35. d *Daemon
  36. ctrl *authorizationController
  37. }
  38. type authorizationController struct {
  39. reqRes authorization.Response // reqRes holds the plugin response to the initial client request
  40. resRes authorization.Response // resRes holds the plugin response to the daemon response
  41. psRequestCnt int // psRequestCnt counts the number of calls to list container request api
  42. psResponseCnt int // psResponseCnt counts the number of calls to list containers response API
  43. requestsURIs []string // requestsURIs stores all request URIs that are sent to the authorization controller
  44. }
  45. func (s *DockerAuthzSuite) SetUpTest(c *check.C) {
  46. s.d = NewDaemon(c)
  47. s.ctrl = &authorizationController{}
  48. }
  49. func (s *DockerAuthzSuite) TearDownTest(c *check.C) {
  50. s.d.Stop()
  51. s.ds.TearDownTest(c)
  52. s.ctrl = nil
  53. }
  54. func (s *DockerAuthzSuite) SetUpSuite(c *check.C) {
  55. mux := http.NewServeMux()
  56. s.server = httptest.NewServer(mux)
  57. c.Assert(s.server, check.NotNil, check.Commentf("Failed to start a HTTP Server"))
  58. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  59. b, err := json.Marshal(plugins.Manifest{Implements: []string{authorization.AuthZApiImplements}})
  60. c.Assert(err, check.IsNil)
  61. w.Write(b)
  62. })
  63. mux.HandleFunc("/AuthZPlugin.AuthZReq", func(w http.ResponseWriter, r *http.Request) {
  64. if s.ctrl.reqRes.Err != "" {
  65. w.WriteHeader(http.StatusInternalServerError)
  66. }
  67. b, err := json.Marshal(s.ctrl.reqRes)
  68. c.Assert(err, check.IsNil)
  69. w.Write(b)
  70. defer r.Body.Close()
  71. body, err := ioutil.ReadAll(r.Body)
  72. c.Assert(err, check.IsNil)
  73. authReq := authorization.Request{}
  74. err = json.Unmarshal(body, &authReq)
  75. c.Assert(err, check.IsNil)
  76. assertBody(c, authReq.RequestURI, authReq.RequestHeaders, authReq.RequestBody)
  77. assertAuthHeaders(c, authReq.RequestHeaders)
  78. // Count only container list api
  79. if strings.HasSuffix(authReq.RequestURI, containerListAPI) {
  80. s.ctrl.psRequestCnt++
  81. }
  82. s.ctrl.requestsURIs = append(s.ctrl.requestsURIs, authReq.RequestURI)
  83. })
  84. mux.HandleFunc("/AuthZPlugin.AuthZRes", func(w http.ResponseWriter, r *http.Request) {
  85. if s.ctrl.resRes.Err != "" {
  86. w.WriteHeader(http.StatusInternalServerError)
  87. }
  88. b, err := json.Marshal(s.ctrl.resRes)
  89. c.Assert(err, check.IsNil)
  90. w.Write(b)
  91. defer r.Body.Close()
  92. body, err := ioutil.ReadAll(r.Body)
  93. c.Assert(err, check.IsNil)
  94. authReq := authorization.Request{}
  95. err = json.Unmarshal(body, &authReq)
  96. c.Assert(err, check.IsNil)
  97. assertBody(c, authReq.RequestURI, authReq.ResponseHeaders, authReq.ResponseBody)
  98. assertAuthHeaders(c, authReq.ResponseHeaders)
  99. // Count only container list api
  100. if strings.HasSuffix(authReq.RequestURI, containerListAPI) {
  101. s.ctrl.psResponseCnt++
  102. }
  103. })
  104. err := os.MkdirAll("/etc/docker/plugins", 0755)
  105. c.Assert(err, checker.IsNil)
  106. fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", testAuthZPlugin)
  107. err = ioutil.WriteFile(fileName, []byte(s.server.URL), 0644)
  108. c.Assert(err, checker.IsNil)
  109. }
  110. // assertAuthHeaders validates authentication headers are removed
  111. func assertAuthHeaders(c *check.C, headers map[string]string) error {
  112. for k := range headers {
  113. if strings.Contains(strings.ToLower(k), "auth") || strings.Contains(strings.ToLower(k), "x-registry") {
  114. c.Errorf("Found authentication headers in request '%v'", headers)
  115. }
  116. }
  117. return nil
  118. }
  119. // assertBody asserts that body is removed for non text/json requests
  120. func assertBody(c *check.C, requestURI string, headers map[string]string, body []byte) {
  121. if strings.Contains(strings.ToLower(requestURI), "auth") && len(body) > 0 {
  122. //return fmt.Errorf("Body included for authentication endpoint %s", string(body))
  123. c.Errorf("Body included for authentication endpoint %s", string(body))
  124. }
  125. for k, v := range headers {
  126. if strings.EqualFold(k, "Content-Type") && strings.HasPrefix(v, "text/") || v == "application/json" {
  127. return
  128. }
  129. }
  130. if len(body) > 0 {
  131. c.Errorf("Body included while it should not (Headers: '%v')", headers)
  132. }
  133. }
  134. func (s *DockerAuthzSuite) TearDownSuite(c *check.C) {
  135. if s.server == nil {
  136. return
  137. }
  138. s.server.Close()
  139. err := os.RemoveAll("/etc/docker/plugins")
  140. c.Assert(err, checker.IsNil)
  141. }
  142. func (s *DockerAuthzSuite) TestAuthZPluginAllowRequest(c *check.C) {
  143. // start the daemon and load busybox, --net=none build fails otherwise
  144. // cause it needs to pull busybox
  145. c.Assert(s.d.StartWithBusybox(), check.IsNil)
  146. // restart the daemon and enable the plugin, otherwise busybox loading
  147. // is blocked by the plugin itself
  148. c.Assert(s.d.Restart("--authorization-plugin="+testAuthZPlugin), check.IsNil)
  149. s.ctrl.reqRes.Allow = true
  150. s.ctrl.resRes.Allow = true
  151. // Ensure command successful
  152. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  153. c.Assert(err, check.IsNil)
  154. id := strings.TrimSpace(out)
  155. assertURIRecorded(c, s.ctrl.requestsURIs, "/containers/create")
  156. assertURIRecorded(c, s.ctrl.requestsURIs, fmt.Sprintf("/containers/%s/start", id))
  157. out, err = s.d.Cmd("ps")
  158. c.Assert(err, check.IsNil)
  159. c.Assert(assertContainerList(out, []string{id}), check.Equals, true)
  160. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  161. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  162. }
  163. func (s *DockerAuthzSuite) TestAuthZPluginDenyRequest(c *check.C) {
  164. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  165. c.Assert(err, check.IsNil)
  166. s.ctrl.reqRes.Allow = false
  167. s.ctrl.reqRes.Msg = unauthorizedMessage
  168. // Ensure command is blocked
  169. res, err := s.d.Cmd("ps")
  170. c.Assert(err, check.NotNil)
  171. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  172. c.Assert(s.ctrl.psResponseCnt, check.Equals, 0)
  173. // Ensure unauthorized message appears in response
  174. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: authorization denied by plugin %s: %s\n", testAuthZPlugin, unauthorizedMessage))
  175. }
  176. func (s *DockerAuthzSuite) TestAuthZPluginDenyResponse(c *check.C) {
  177. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  178. c.Assert(err, check.IsNil)
  179. s.ctrl.reqRes.Allow = true
  180. s.ctrl.resRes.Allow = false
  181. s.ctrl.resRes.Msg = unauthorizedMessage
  182. // Ensure command is blocked
  183. res, err := s.d.Cmd("ps")
  184. c.Assert(err, check.NotNil)
  185. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  186. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  187. // Ensure unauthorized message appears in response
  188. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: authorization denied by plugin %s: %s\n", testAuthZPlugin, unauthorizedMessage))
  189. }
  190. // TestAuthZPluginAllowEventStream verifies event stream propogates correctly after request pass through by the authorization plugin
  191. func (s *DockerAuthzSuite) TestAuthZPluginAllowEventStream(c *check.C) {
  192. testRequires(c, DaemonIsLinux)
  193. // Start the authorization plugin
  194. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  195. c.Assert(err, check.IsNil)
  196. s.ctrl.reqRes.Allow = true
  197. s.ctrl.resRes.Allow = true
  198. startTime := strconv.FormatInt(daemonTime(c).Unix(), 10)
  199. // Add another command to to enable event pipelining
  200. eventsCmd := exec.Command(s.d.cmd.Path, "--host", s.d.sock(), "events", "--since", startTime)
  201. stdout, err := eventsCmd.StdoutPipe()
  202. if err != nil {
  203. c.Assert(err, check.IsNil)
  204. }
  205. observer := eventObserver{
  206. buffer: new(bytes.Buffer),
  207. command: eventsCmd,
  208. scanner: bufio.NewScanner(stdout),
  209. startTime: startTime,
  210. }
  211. err = observer.Start()
  212. c.Assert(err, checker.IsNil)
  213. defer observer.Stop()
  214. // Create a container and wait for the creation events
  215. _, err = s.d.Cmd("pull", "busybox")
  216. c.Assert(err, check.IsNil)
  217. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  218. c.Assert(err, check.IsNil)
  219. containerID := strings.TrimSpace(out)
  220. events := map[string]chan bool{
  221. "create": make(chan bool),
  222. "start": make(chan bool),
  223. }
  224. matcher := matchEventLine(containerID, "container", events)
  225. processor := processEventMatch(events)
  226. go observer.Match(matcher, processor)
  227. // Ensure all events are received
  228. for event, eventChannel := range events {
  229. select {
  230. case <-time.After(5 * time.Second):
  231. // Fail the test
  232. observer.CheckEventError(c, containerID, event, matcher)
  233. c.FailNow()
  234. case <-eventChannel:
  235. // Ignore, event received
  236. }
  237. }
  238. // Ensure both events and container endpoints are passed to the authorization plugin
  239. assertURIRecorded(c, s.ctrl.requestsURIs, "/events")
  240. assertURIRecorded(c, s.ctrl.requestsURIs, "/containers/create")
  241. assertURIRecorded(c, s.ctrl.requestsURIs, fmt.Sprintf("/containers/%s/start", containerID))
  242. }
  243. func (s *DockerAuthzSuite) TestAuthZPluginErrorResponse(c *check.C) {
  244. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  245. c.Assert(err, check.IsNil)
  246. s.ctrl.reqRes.Allow = true
  247. s.ctrl.resRes.Err = errorMessage
  248. // Ensure command is blocked
  249. res, err := s.d.Cmd("ps")
  250. c.Assert(err, check.NotNil)
  251. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s\n", testAuthZPlugin, authorization.AuthZApiResponse, errorMessage))
  252. }
  253. func (s *DockerAuthzSuite) TestAuthZPluginErrorRequest(c *check.C) {
  254. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  255. c.Assert(err, check.IsNil)
  256. s.ctrl.reqRes.Err = errorMessage
  257. // Ensure command is blocked
  258. res, err := s.d.Cmd("ps")
  259. c.Assert(err, check.NotNil)
  260. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s\n", testAuthZPlugin, authorization.AuthZApiRequest, errorMessage))
  261. }
  262. func (s *DockerAuthzSuite) TestAuthZPluginEnsureNoDuplicatePluginRegistration(c *check.C) {
  263. c.Assert(s.d.Start("--authorization-plugin="+testAuthZPlugin, "--authorization-plugin="+testAuthZPlugin), check.IsNil)
  264. s.ctrl.reqRes.Allow = true
  265. s.ctrl.resRes.Allow = true
  266. out, err := s.d.Cmd("ps")
  267. c.Assert(err, check.IsNil, check.Commentf(out))
  268. // assert plugin is only called once..
  269. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  270. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  271. }
  272. // assertURIRecorded verifies that the given URI was sent and recorded in the authz plugin
  273. func assertURIRecorded(c *check.C, uris []string, uri string) {
  274. var found bool
  275. for _, u := range uris {
  276. if strings.Contains(u, uri) {
  277. found = true
  278. break
  279. }
  280. }
  281. if !found {
  282. c.Fatalf("Expected to find URI '%s', recorded uris '%s'", uri, strings.Join(uris, ","))
  283. }
  284. }