docker_cli_authz_unix_test.go 12 KB

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