docker_cli_authz_unix_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  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/daemon"
  21. "github.com/docker/docker/pkg/authorization"
  22. "github.com/docker/docker/pkg/integration/checker"
  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: experimentalDaemon,
  58. })
  59. s.ctrl = &authorizationController{}
  60. }
  61. func (s *DockerAuthzSuite) TearDownTest(c *check.C) {
  62. if s.d != nil {
  63. s.d.Stop()
  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. // start the daemon and load busybox, --net=none build fails otherwise
  176. // cause it needs to pull busybox
  177. c.Assert(s.d.Start("--authorization-plugin="+testAuthZPlugin), check.IsNil)
  178. s.ctrl.reqRes.Allow = true
  179. s.ctrl.resRes.Allow = true
  180. c.Assert(s.d.LoadBusybox(), check.IsNil)
  181. // Ensure command successful
  182. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  183. c.Assert(err, check.IsNil)
  184. id := strings.TrimSpace(out)
  185. assertURIRecorded(c, s.ctrl.requestsURIs, "/containers/create")
  186. assertURIRecorded(c, s.ctrl.requestsURIs, fmt.Sprintf("/containers/%s/start", id))
  187. out, err = s.d.Cmd("ps")
  188. c.Assert(err, check.IsNil)
  189. c.Assert(assertContainerList(out, []string{id}), check.Equals, true)
  190. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  191. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  192. }
  193. func (s *DockerAuthzSuite) TestAuthZPluginTls(c *check.C) {
  194. const testDaemonHTTPSAddr = "tcp://localhost:4271"
  195. // start the daemon and load busybox, --net=none build fails otherwise
  196. // cause it needs to pull busybox
  197. if err := s.d.Start(
  198. "--authorization-plugin="+testAuthZPlugin,
  199. "--tlsverify",
  200. "--tlscacert",
  201. "fixtures/https/ca.pem",
  202. "--tlscert",
  203. "fixtures/https/server-cert.pem",
  204. "--tlskey",
  205. "fixtures/https/server-key.pem",
  206. "-H", testDaemonHTTPSAddr); err != nil {
  207. c.Fatalf("Could not start daemon with busybox: %v", err)
  208. }
  209. s.ctrl.reqRes.Allow = true
  210. s.ctrl.resRes.Allow = true
  211. out, _ := dockerCmd(
  212. c,
  213. "--tlsverify",
  214. "--tlscacert", "fixtures/https/ca.pem",
  215. "--tlscert", "fixtures/https/client-cert.pem",
  216. "--tlskey", "fixtures/https/client-key.pem",
  217. "-H",
  218. testDaemonHTTPSAddr,
  219. "version",
  220. )
  221. if !strings.Contains(out, "Server") {
  222. c.Fatalf("docker version should return information of server side")
  223. }
  224. c.Assert(s.ctrl.reqUser, check.Equals, "client")
  225. c.Assert(s.ctrl.resUser, check.Equals, "client")
  226. }
  227. func (s *DockerAuthzSuite) TestAuthZPluginDenyRequest(c *check.C) {
  228. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  229. c.Assert(err, check.IsNil)
  230. s.ctrl.reqRes.Allow = false
  231. s.ctrl.reqRes.Msg = unauthorizedMessage
  232. // Ensure command is blocked
  233. res, err := s.d.Cmd("ps")
  234. c.Assert(err, check.NotNil)
  235. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  236. c.Assert(s.ctrl.psResponseCnt, check.Equals, 0)
  237. // Ensure unauthorized message appears in response
  238. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: authorization denied by plugin %s: %s\n", testAuthZPlugin, unauthorizedMessage))
  239. }
  240. // TestAuthZPluginAPIDenyResponse validates that when authorization plugin deny the request, the status code is forbidden
  241. func (s *DockerAuthzSuite) TestAuthZPluginAPIDenyResponse(c *check.C) {
  242. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  243. c.Assert(err, check.IsNil)
  244. s.ctrl.reqRes.Allow = false
  245. s.ctrl.resRes.Msg = unauthorizedMessage
  246. daemonURL, err := url.Parse(s.d.Sock())
  247. conn, err := net.DialTimeout(daemonURL.Scheme, daemonURL.Path, time.Second*10)
  248. c.Assert(err, check.IsNil)
  249. client := httputil.NewClientConn(conn, nil)
  250. req, err := http.NewRequest("GET", "/version", nil)
  251. c.Assert(err, check.IsNil)
  252. resp, err := client.Do(req)
  253. c.Assert(err, check.IsNil)
  254. c.Assert(resp.StatusCode, checker.Equals, http.StatusForbidden)
  255. c.Assert(err, checker.IsNil)
  256. }
  257. func (s *DockerAuthzSuite) TestAuthZPluginDenyResponse(c *check.C) {
  258. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  259. c.Assert(err, check.IsNil)
  260. s.ctrl.reqRes.Allow = true
  261. s.ctrl.resRes.Allow = false
  262. s.ctrl.resRes.Msg = unauthorizedMessage
  263. // Ensure command is blocked
  264. res, err := s.d.Cmd("ps")
  265. c.Assert(err, check.NotNil)
  266. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  267. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  268. // Ensure unauthorized message appears in response
  269. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: authorization denied by plugin %s: %s\n", testAuthZPlugin, unauthorizedMessage))
  270. }
  271. // TestAuthZPluginAllowEventStream verifies event stream propagates correctly after request pass through by the authorization plugin
  272. func (s *DockerAuthzSuite) TestAuthZPluginAllowEventStream(c *check.C) {
  273. testRequires(c, DaemonIsLinux)
  274. // start the daemon and load busybox to avoid pulling busybox from Docker Hub
  275. c.Assert(s.d.Start("--authorization-plugin="+testAuthZPlugin), check.IsNil)
  276. s.ctrl.reqRes.Allow = true
  277. s.ctrl.resRes.Allow = true
  278. c.Assert(s.d.LoadBusybox(), check.IsNil)
  279. startTime := strconv.FormatInt(daemonTime(c).Unix(), 10)
  280. // Add another command to to enable event pipelining
  281. eventsCmd := exec.Command(dockerBinary, "--host", s.d.Sock(), "events", "--since", startTime)
  282. stdout, err := eventsCmd.StdoutPipe()
  283. if err != nil {
  284. c.Assert(err, check.IsNil)
  285. }
  286. observer := eventObserver{
  287. buffer: new(bytes.Buffer),
  288. command: eventsCmd,
  289. scanner: bufio.NewScanner(stdout),
  290. startTime: startTime,
  291. }
  292. err = observer.Start()
  293. c.Assert(err, checker.IsNil)
  294. defer observer.Stop()
  295. // Create a container and wait for the creation events
  296. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  297. c.Assert(err, check.IsNil, check.Commentf(out))
  298. containerID := strings.TrimSpace(out)
  299. c.Assert(s.d.WaitRun(containerID), checker.IsNil)
  300. events := map[string]chan bool{
  301. "create": make(chan bool, 1),
  302. "start": make(chan bool, 1),
  303. }
  304. matcher := matchEventLine(containerID, "container", events)
  305. processor := processEventMatch(events)
  306. go observer.Match(matcher, processor)
  307. // Ensure all events are received
  308. for event, eventChannel := range events {
  309. select {
  310. case <-time.After(30 * time.Second):
  311. // Fail the test
  312. observer.CheckEventError(c, containerID, event, matcher)
  313. c.FailNow()
  314. case <-eventChannel:
  315. // Ignore, event received
  316. }
  317. }
  318. // Ensure both events and container endpoints are passed to the authorization plugin
  319. assertURIRecorded(c, s.ctrl.requestsURIs, "/events")
  320. assertURIRecorded(c, s.ctrl.requestsURIs, "/containers/create")
  321. assertURIRecorded(c, s.ctrl.requestsURIs, fmt.Sprintf("/containers/%s/start", containerID))
  322. }
  323. func (s *DockerAuthzSuite) TestAuthZPluginErrorResponse(c *check.C) {
  324. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  325. c.Assert(err, check.IsNil)
  326. s.ctrl.reqRes.Allow = true
  327. s.ctrl.resRes.Err = errorMessage
  328. // Ensure command is blocked
  329. res, err := s.d.Cmd("ps")
  330. c.Assert(err, check.NotNil)
  331. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s\n", testAuthZPlugin, authorization.AuthZApiResponse, errorMessage))
  332. }
  333. func (s *DockerAuthzSuite) TestAuthZPluginErrorRequest(c *check.C) {
  334. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  335. c.Assert(err, check.IsNil)
  336. s.ctrl.reqRes.Err = errorMessage
  337. // Ensure command is blocked
  338. res, err := s.d.Cmd("ps")
  339. c.Assert(err, check.NotNil)
  340. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s\n", testAuthZPlugin, authorization.AuthZApiRequest, errorMessage))
  341. }
  342. func (s *DockerAuthzSuite) TestAuthZPluginEnsureNoDuplicatePluginRegistration(c *check.C) {
  343. c.Assert(s.d.Start("--authorization-plugin="+testAuthZPlugin, "--authorization-plugin="+testAuthZPlugin), check.IsNil)
  344. s.ctrl.reqRes.Allow = true
  345. s.ctrl.resRes.Allow = true
  346. out, err := s.d.Cmd("ps")
  347. c.Assert(err, check.IsNil, check.Commentf(out))
  348. // assert plugin is only called once..
  349. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  350. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  351. }
  352. func (s *DockerAuthzSuite) TestAuthZPluginEnsureLoadImportWorking(c *check.C) {
  353. c.Assert(s.d.Start("--authorization-plugin="+testAuthZPlugin, "--authorization-plugin="+testAuthZPlugin), check.IsNil)
  354. s.ctrl.reqRes.Allow = true
  355. s.ctrl.resRes.Allow = true
  356. c.Assert(s.d.LoadBusybox(), check.IsNil)
  357. tmp, err := ioutil.TempDir("", "test-authz-load-import")
  358. c.Assert(err, check.IsNil)
  359. defer os.RemoveAll(tmp)
  360. savedImagePath := filepath.Join(tmp, "save.tar")
  361. out, err := s.d.Cmd("save", "-o", savedImagePath, "busybox")
  362. c.Assert(err, check.IsNil, check.Commentf(out))
  363. out, err = s.d.Cmd("load", "--input", savedImagePath)
  364. c.Assert(err, check.IsNil, check.Commentf(out))
  365. exportedImagePath := filepath.Join(tmp, "export.tar")
  366. out, err = s.d.Cmd("run", "-d", "--name", "testexport", "busybox")
  367. c.Assert(err, check.IsNil, check.Commentf(out))
  368. out, err = s.d.Cmd("export", "-o", exportedImagePath, "testexport")
  369. c.Assert(err, check.IsNil, check.Commentf(out))
  370. out, err = s.d.Cmd("import", exportedImagePath)
  371. c.Assert(err, check.IsNil, check.Commentf(out))
  372. }
  373. func (s *DockerAuthzSuite) TestAuthZPluginHeader(c *check.C) {
  374. c.Assert(s.d.Start("--debug", "--authorization-plugin="+testAuthZPlugin), check.IsNil)
  375. s.ctrl.reqRes.Allow = true
  376. s.ctrl.resRes.Allow = true
  377. c.Assert(s.d.LoadBusybox(), check.IsNil)
  378. daemonURL, err := url.Parse(s.d.Sock())
  379. conn, err := net.DialTimeout(daemonURL.Scheme, daemonURL.Path, time.Second*10)
  380. c.Assert(err, check.IsNil)
  381. client := httputil.NewClientConn(conn, nil)
  382. req, err := http.NewRequest("GET", "/version", nil)
  383. c.Assert(err, check.IsNil)
  384. resp, err := client.Do(req)
  385. c.Assert(err, check.IsNil)
  386. c.Assert(resp.Header["Content-Type"][0], checker.Equals, "application/json")
  387. }
  388. // assertURIRecorded verifies that the given URI was sent and recorded in the authz plugin
  389. func assertURIRecorded(c *check.C, uris []string, uri string) {
  390. var found bool
  391. for _, u := range uris {
  392. if strings.Contains(u, uri) {
  393. found = true
  394. break
  395. }
  396. }
  397. if !found {
  398. c.Fatalf("Expected to find URI '%s', recorded uris '%s'", uri, strings.Join(uris, ","))
  399. }
  400. }