docker_cli_authz_unix_test.go 14 KB

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