docker_cli_authz_unix_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  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. "path/filepath"
  11. "strings"
  12. "bufio"
  13. "bytes"
  14. "os/exec"
  15. "strconv"
  16. "time"
  17. "net"
  18. "net/http/httputil"
  19. "net/url"
  20. "github.com/docker/docker/integration-cli/checker"
  21. "github.com/docker/docker/integration-cli/daemon"
  22. "github.com/docker/docker/pkg/authorization"
  23. "github.com/docker/docker/pkg/plugins"
  24. "github.com/go-check/check"
  25. )
  26. const (
  27. testAuthZPlugin = "authzplugin"
  28. unauthorizedMessage = "User unauthorized authz plugin"
  29. errorMessage = "something went wrong..."
  30. containerListAPI = "/containers/json"
  31. )
  32. var (
  33. alwaysAllowed = []string{"/_ping", "/info"}
  34. )
  35. func init() {
  36. check.Suite(&DockerAuthzSuite{
  37. ds: &DockerSuite{},
  38. })
  39. }
  40. type DockerAuthzSuite struct {
  41. server *httptest.Server
  42. ds *DockerSuite
  43. d *daemon.Daemon
  44. ctrl *authorizationController
  45. }
  46. type authorizationController struct {
  47. reqRes authorization.Response // reqRes holds the plugin response to the initial client request
  48. resRes authorization.Response // resRes holds the plugin response to the daemon response
  49. psRequestCnt int // psRequestCnt counts the number of calls to list container request api
  50. psResponseCnt int // psResponseCnt counts the number of calls to list containers response API
  51. requestsURIs []string // requestsURIs stores all request URIs that are sent to the authorization controller
  52. reqUser string
  53. resUser string
  54. }
  55. func (s *DockerAuthzSuite) SetUpTest(c *check.C) {
  56. s.d = daemon.New(c, dockerBinary, dockerdBinary, daemon.Config{
  57. Experimental: testEnv.ExperimentalDaemon(),
  58. })
  59. s.ctrl = &authorizationController{}
  60. }
  61. func (s *DockerAuthzSuite) TearDownTest(c *check.C) {
  62. if s.d != nil {
  63. s.d.Stop(c)
  64. s.ds.TearDownTest(c)
  65. s.ctrl = nil
  66. }
  67. }
  68. func (s *DockerAuthzSuite) SetUpSuite(c *check.C) {
  69. mux := http.NewServeMux()
  70. s.server = httptest.NewServer(mux)
  71. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  72. b, err := json.Marshal(plugins.Manifest{Implements: []string{authorization.AuthZApiImplements}})
  73. c.Assert(err, check.IsNil)
  74. w.Write(b)
  75. })
  76. mux.HandleFunc("/AuthZPlugin.AuthZReq", func(w http.ResponseWriter, r *http.Request) {
  77. defer r.Body.Close()
  78. body, err := ioutil.ReadAll(r.Body)
  79. c.Assert(err, check.IsNil)
  80. authReq := authorization.Request{}
  81. err = json.Unmarshal(body, &authReq)
  82. c.Assert(err, check.IsNil)
  83. assertBody(c, authReq.RequestURI, authReq.RequestHeaders, authReq.RequestBody)
  84. assertAuthHeaders(c, authReq.RequestHeaders)
  85. // Count only container list api
  86. if strings.HasSuffix(authReq.RequestURI, containerListAPI) {
  87. s.ctrl.psRequestCnt++
  88. }
  89. s.ctrl.requestsURIs = append(s.ctrl.requestsURIs, authReq.RequestURI)
  90. reqRes := s.ctrl.reqRes
  91. if isAllowed(authReq.RequestURI) {
  92. reqRes = authorization.Response{Allow: true}
  93. }
  94. if reqRes.Err != "" {
  95. w.WriteHeader(http.StatusInternalServerError)
  96. }
  97. b, err := json.Marshal(reqRes)
  98. c.Assert(err, check.IsNil)
  99. s.ctrl.reqUser = authReq.User
  100. w.Write(b)
  101. })
  102. mux.HandleFunc("/AuthZPlugin.AuthZRes", func(w http.ResponseWriter, r *http.Request) {
  103. defer r.Body.Close()
  104. body, err := ioutil.ReadAll(r.Body)
  105. c.Assert(err, check.IsNil)
  106. authReq := authorization.Request{}
  107. err = json.Unmarshal(body, &authReq)
  108. c.Assert(err, check.IsNil)
  109. assertBody(c, authReq.RequestURI, authReq.ResponseHeaders, authReq.ResponseBody)
  110. assertAuthHeaders(c, authReq.ResponseHeaders)
  111. // Count only container list api
  112. if strings.HasSuffix(authReq.RequestURI, containerListAPI) {
  113. s.ctrl.psResponseCnt++
  114. }
  115. resRes := s.ctrl.resRes
  116. if isAllowed(authReq.RequestURI) {
  117. resRes = authorization.Response{Allow: true}
  118. }
  119. if resRes.Err != "" {
  120. w.WriteHeader(http.StatusInternalServerError)
  121. }
  122. b, err := json.Marshal(resRes)
  123. c.Assert(err, check.IsNil)
  124. s.ctrl.resUser = authReq.User
  125. w.Write(b)
  126. })
  127. err := os.MkdirAll("/etc/docker/plugins", 0755)
  128. c.Assert(err, checker.IsNil)
  129. fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", testAuthZPlugin)
  130. err = ioutil.WriteFile(fileName, []byte(s.server.URL), 0644)
  131. c.Assert(err, checker.IsNil)
  132. }
  133. // check for always allowed endpoints to not inhibit test framework functions
  134. func isAllowed(reqURI string) bool {
  135. for _, endpoint := range alwaysAllowed {
  136. if strings.HasSuffix(reqURI, endpoint) {
  137. return true
  138. }
  139. }
  140. return false
  141. }
  142. // assertAuthHeaders validates authentication headers are removed
  143. func assertAuthHeaders(c *check.C, headers map[string]string) error {
  144. for k := range headers {
  145. if strings.Contains(strings.ToLower(k), "auth") || strings.Contains(strings.ToLower(k), "x-registry") {
  146. c.Errorf("Found authentication headers in request '%v'", headers)
  147. }
  148. }
  149. return nil
  150. }
  151. // assertBody asserts that body is removed for non text/json requests
  152. func assertBody(c *check.C, requestURI string, headers map[string]string, body []byte) {
  153. if strings.Contains(strings.ToLower(requestURI), "auth") && len(body) > 0 {
  154. //return fmt.Errorf("Body included for authentication endpoint %s", string(body))
  155. c.Errorf("Body included for authentication endpoint %s", string(body))
  156. }
  157. for k, v := range headers {
  158. if strings.EqualFold(k, "Content-Type") && strings.HasPrefix(v, "text/") || v == "application/json" {
  159. return
  160. }
  161. }
  162. if len(body) > 0 {
  163. c.Errorf("Body included while it should not (Headers: '%v')", headers)
  164. }
  165. }
  166. func (s *DockerAuthzSuite) TearDownSuite(c *check.C) {
  167. if s.server == nil {
  168. return
  169. }
  170. s.server.Close()
  171. err := os.RemoveAll("/etc/docker/plugins")
  172. c.Assert(err, checker.IsNil)
  173. }
  174. func (s *DockerAuthzSuite) TestAuthZPluginAllowRequest(c *check.C) {
  175. existingContainers := ExistingContainerIDs(c)
  176. // start the daemon and load busybox, --net=none build fails otherwise
  177. // cause it needs to pull busybox
  178. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin)
  179. s.ctrl.reqRes.Allow = true
  180. s.ctrl.resRes.Allow = true
  181. s.d.LoadBusybox(c)
  182. // Ensure command successful
  183. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  184. c.Assert(err, check.IsNil)
  185. id := strings.TrimSpace(out)
  186. assertURIRecorded(c, s.ctrl.requestsURIs, "/containers/create")
  187. assertURIRecorded(c, s.ctrl.requestsURIs, fmt.Sprintf("/containers/%s/start", id))
  188. out, err = s.d.Cmd("ps")
  189. c.Assert(err, check.IsNil)
  190. c.Assert(assertContainerList(RemoveOutputForExistingElements(out, existingContainers), []string{id}), check.Equals, true)
  191. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  192. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  193. }
  194. func (s *DockerAuthzSuite) TestAuthZPluginTls(c *check.C) {
  195. const testDaemonHTTPSAddr = "tcp://localhost:4271"
  196. // start the daemon and load busybox, --net=none build fails otherwise
  197. // cause it needs to pull busybox
  198. s.d.Start(c,
  199. "--authorization-plugin="+testAuthZPlugin,
  200. "--tlsverify",
  201. "--tlscacert",
  202. "fixtures/https/ca.pem",
  203. "--tlscert",
  204. "fixtures/https/server-cert.pem",
  205. "--tlskey",
  206. "fixtures/https/server-key.pem",
  207. "-H", testDaemonHTTPSAddr)
  208. s.ctrl.reqRes.Allow = true
  209. s.ctrl.resRes.Allow = true
  210. out, _ := dockerCmd(
  211. c,
  212. "--tlsverify",
  213. "--tlscacert", "fixtures/https/ca.pem",
  214. "--tlscert", "fixtures/https/client-cert.pem",
  215. "--tlskey", "fixtures/https/client-key.pem",
  216. "-H",
  217. testDaemonHTTPSAddr,
  218. "version",
  219. )
  220. if !strings.Contains(out, "Server") {
  221. c.Fatalf("docker version should return information of server side")
  222. }
  223. c.Assert(s.ctrl.reqUser, check.Equals, "client")
  224. c.Assert(s.ctrl.resUser, check.Equals, "client")
  225. }
  226. func (s *DockerAuthzSuite) TestAuthZPluginDenyRequest(c *check.C) {
  227. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin)
  228. s.ctrl.reqRes.Allow = false
  229. s.ctrl.reqRes.Msg = unauthorizedMessage
  230. // Ensure command is blocked
  231. res, err := s.d.Cmd("ps")
  232. c.Assert(err, check.NotNil)
  233. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  234. c.Assert(s.ctrl.psResponseCnt, check.Equals, 0)
  235. // Ensure unauthorized message appears in response
  236. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: authorization denied by plugin %s: %s\n", testAuthZPlugin, unauthorizedMessage))
  237. }
  238. // TestAuthZPluginAPIDenyResponse validates that when authorization plugin deny the request, the status code is forbidden
  239. func (s *DockerAuthzSuite) TestAuthZPluginAPIDenyResponse(c *check.C) {
  240. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin)
  241. s.ctrl.reqRes.Allow = false
  242. s.ctrl.resRes.Msg = unauthorizedMessage
  243. daemonURL, err := url.Parse(s.d.Sock())
  244. conn, err := net.DialTimeout(daemonURL.Scheme, daemonURL.Path, time.Second*10)
  245. c.Assert(err, check.IsNil)
  246. client := httputil.NewClientConn(conn, nil)
  247. req, err := http.NewRequest("GET", "/version", nil)
  248. c.Assert(err, check.IsNil)
  249. resp, err := client.Do(req)
  250. c.Assert(err, check.IsNil)
  251. c.Assert(resp.StatusCode, checker.Equals, http.StatusForbidden)
  252. c.Assert(err, checker.IsNil)
  253. }
  254. func (s *DockerAuthzSuite) TestAuthZPluginDenyResponse(c *check.C) {
  255. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin)
  256. s.ctrl.reqRes.Allow = true
  257. s.ctrl.resRes.Allow = false
  258. s.ctrl.resRes.Msg = unauthorizedMessage
  259. // Ensure command is blocked
  260. res, err := s.d.Cmd("ps")
  261. c.Assert(err, check.NotNil)
  262. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  263. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  264. // Ensure unauthorized message appears in response
  265. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: authorization denied by plugin %s: %s\n", testAuthZPlugin, unauthorizedMessage))
  266. }
  267. // TestAuthZPluginAllowEventStream verifies event stream propagates correctly after request pass through by the authorization plugin
  268. func (s *DockerAuthzSuite) TestAuthZPluginAllowEventStream(c *check.C) {
  269. testRequires(c, DaemonIsLinux)
  270. // start the daemon and load busybox to avoid pulling busybox from Docker Hub
  271. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin)
  272. s.ctrl.reqRes.Allow = true
  273. s.ctrl.resRes.Allow = true
  274. s.d.LoadBusybox(c)
  275. startTime := strconv.FormatInt(daemonTime(c).Unix(), 10)
  276. // Add another command to to enable event pipelining
  277. eventsCmd := exec.Command(dockerBinary, "--host", s.d.Sock(), "events", "--since", startTime)
  278. stdout, err := eventsCmd.StdoutPipe()
  279. if err != nil {
  280. c.Assert(err, check.IsNil)
  281. }
  282. observer := eventObserver{
  283. buffer: new(bytes.Buffer),
  284. command: eventsCmd,
  285. scanner: bufio.NewScanner(stdout),
  286. startTime: startTime,
  287. }
  288. err = observer.Start()
  289. c.Assert(err, checker.IsNil)
  290. defer observer.Stop()
  291. // Create a container and wait for the creation events
  292. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  293. c.Assert(err, check.IsNil, check.Commentf(out))
  294. containerID := strings.TrimSpace(out)
  295. c.Assert(s.d.WaitRun(containerID), checker.IsNil)
  296. events := map[string]chan bool{
  297. "create": make(chan bool, 1),
  298. "start": make(chan bool, 1),
  299. }
  300. matcher := matchEventLine(containerID, "container", events)
  301. processor := processEventMatch(events)
  302. go observer.Match(matcher, processor)
  303. // Ensure all events are received
  304. for event, eventChannel := range events {
  305. select {
  306. case <-time.After(30 * time.Second):
  307. // Fail the test
  308. observer.CheckEventError(c, containerID, event, matcher)
  309. c.FailNow()
  310. case <-eventChannel:
  311. // Ignore, event received
  312. }
  313. }
  314. // Ensure both events and container endpoints are passed to the authorization plugin
  315. assertURIRecorded(c, s.ctrl.requestsURIs, "/events")
  316. assertURIRecorded(c, s.ctrl.requestsURIs, "/containers/create")
  317. assertURIRecorded(c, s.ctrl.requestsURIs, fmt.Sprintf("/containers/%s/start", containerID))
  318. }
  319. func (s *DockerAuthzSuite) TestAuthZPluginErrorResponse(c *check.C) {
  320. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin)
  321. s.ctrl.reqRes.Allow = true
  322. s.ctrl.resRes.Err = errorMessage
  323. // Ensure command is blocked
  324. res, err := s.d.Cmd("ps")
  325. c.Assert(err, check.NotNil)
  326. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s\n", testAuthZPlugin, authorization.AuthZApiResponse, errorMessage))
  327. }
  328. func (s *DockerAuthzSuite) TestAuthZPluginErrorRequest(c *check.C) {
  329. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin)
  330. s.ctrl.reqRes.Err = errorMessage
  331. // Ensure command is blocked
  332. res, err := s.d.Cmd("ps")
  333. c.Assert(err, check.NotNil)
  334. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s\n", testAuthZPlugin, authorization.AuthZApiRequest, errorMessage))
  335. }
  336. func (s *DockerAuthzSuite) TestAuthZPluginEnsureNoDuplicatePluginRegistration(c *check.C) {
  337. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin, "--authorization-plugin="+testAuthZPlugin)
  338. s.ctrl.reqRes.Allow = true
  339. s.ctrl.resRes.Allow = true
  340. out, err := s.d.Cmd("ps")
  341. c.Assert(err, check.IsNil, check.Commentf(out))
  342. // assert plugin is only called once..
  343. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  344. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  345. }
  346. func (s *DockerAuthzSuite) TestAuthZPluginEnsureLoadImportWorking(c *check.C) {
  347. s.d.Start(c, "--authorization-plugin="+testAuthZPlugin, "--authorization-plugin="+testAuthZPlugin)
  348. s.ctrl.reqRes.Allow = true
  349. s.ctrl.resRes.Allow = true
  350. s.d.LoadBusybox(c)
  351. tmp, err := ioutil.TempDir("", "test-authz-load-import")
  352. c.Assert(err, check.IsNil)
  353. defer os.RemoveAll(tmp)
  354. savedImagePath := filepath.Join(tmp, "save.tar")
  355. out, err := s.d.Cmd("save", "-o", savedImagePath, "busybox")
  356. c.Assert(err, check.IsNil, check.Commentf(out))
  357. out, err = s.d.Cmd("load", "--input", savedImagePath)
  358. c.Assert(err, check.IsNil, check.Commentf(out))
  359. exportedImagePath := filepath.Join(tmp, "export.tar")
  360. out, err = s.d.Cmd("run", "-d", "--name", "testexport", "busybox")
  361. c.Assert(err, check.IsNil, check.Commentf(out))
  362. out, err = s.d.Cmd("export", "-o", exportedImagePath, "testexport")
  363. c.Assert(err, check.IsNil, check.Commentf(out))
  364. out, err = s.d.Cmd("import", exportedImagePath)
  365. c.Assert(err, check.IsNil, check.Commentf(out))
  366. }
  367. func (s *DockerAuthzSuite) TestAuthZPluginHeader(c *check.C) {
  368. s.d.Start(c, "--debug", "--authorization-plugin="+testAuthZPlugin)
  369. s.ctrl.reqRes.Allow = true
  370. s.ctrl.resRes.Allow = true
  371. s.d.LoadBusybox(c)
  372. daemonURL, err := url.Parse(s.d.Sock())
  373. conn, err := net.DialTimeout(daemonURL.Scheme, daemonURL.Path, time.Second*10)
  374. c.Assert(err, check.IsNil)
  375. client := httputil.NewClientConn(conn, nil)
  376. req, err := http.NewRequest("GET", "/version", nil)
  377. c.Assert(err, check.IsNil)
  378. resp, err := client.Do(req)
  379. c.Assert(err, check.IsNil)
  380. c.Assert(resp.Header["Content-Type"][0], checker.Equals, "application/json")
  381. }
  382. // assertURIRecorded verifies that the given URI was sent and recorded in the authz plugin
  383. func assertURIRecorded(c *check.C, uris []string, uri string) {
  384. var found bool
  385. for _, u := range uris {
  386. if strings.Contains(u, uri) {
  387. found = true
  388. break
  389. }
  390. }
  391. if !found {
  392. c.Fatalf("Expected to find URI '%s', recorded uris '%s'", uri, strings.Join(uris, ","))
  393. }
  394. }