docker_cli_authz_unix_test.go 11 KB

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