docker_cli_authz_unix_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  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/pkg/authorization"
  21. "github.com/docker/docker/pkg/integration/checker"
  22. "github.com/docker/docker/pkg/plugins"
  23. "github.com/go-check/check"
  24. )
  25. const (
  26. testAuthZPlugin = "authzplugin"
  27. unauthorizedMessage = "User unauthorized authz plugin"
  28. errorMessage = "something went wrong..."
  29. containerListAPI = "/containers/json"
  30. )
  31. var (
  32. alwaysAllowed = []string{"/_ping", "/info"}
  33. )
  34. func init() {
  35. check.Suite(&DockerAuthzSuite{
  36. ds: &DockerSuite{},
  37. })
  38. }
  39. type DockerAuthzSuite struct {
  40. server *httptest.Server
  41. ds *DockerSuite
  42. d *Daemon
  43. ctrl *authorizationController
  44. }
  45. type authorizationController struct {
  46. reqRes authorization.Response // reqRes holds the plugin response to the initial client request
  47. resRes authorization.Response // resRes holds the plugin response to the daemon response
  48. psRequestCnt int // psRequestCnt counts the number of calls to list container request api
  49. psResponseCnt int // psResponseCnt counts the number of calls to list containers response API
  50. requestsURIs []string // requestsURIs stores all request URIs that are sent to the authorization controller
  51. reqUser string
  52. resUser string
  53. }
  54. func (s *DockerAuthzSuite) SetUpTest(c *check.C) {
  55. s.d = NewDaemon(c)
  56. s.ctrl = &authorizationController{}
  57. }
  58. func (s *DockerAuthzSuite) TearDownTest(c *check.C) {
  59. s.d.Stop()
  60. s.ds.TearDownTest(c)
  61. s.ctrl = nil
  62. }
  63. func (s *DockerAuthzSuite) SetUpSuite(c *check.C) {
  64. mux := http.NewServeMux()
  65. s.server = httptest.NewServer(mux)
  66. c.Assert(s.server, check.NotNil, check.Commentf("Failed to start an HTTP Server"))
  67. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  68. b, err := json.Marshal(plugins.Manifest{Implements: []string{authorization.AuthZApiImplements}})
  69. c.Assert(err, check.IsNil)
  70. w.Write(b)
  71. })
  72. mux.HandleFunc("/AuthZPlugin.AuthZReq", func(w http.ResponseWriter, r *http.Request) {
  73. defer r.Body.Close()
  74. body, err := ioutil.ReadAll(r.Body)
  75. c.Assert(err, check.IsNil)
  76. authReq := authorization.Request{}
  77. err = json.Unmarshal(body, &authReq)
  78. c.Assert(err, check.IsNil)
  79. assertBody(c, authReq.RequestURI, authReq.RequestHeaders, authReq.RequestBody)
  80. assertAuthHeaders(c, authReq.RequestHeaders)
  81. // Count only container list api
  82. if strings.HasSuffix(authReq.RequestURI, containerListAPI) {
  83. s.ctrl.psRequestCnt++
  84. }
  85. s.ctrl.requestsURIs = append(s.ctrl.requestsURIs, authReq.RequestURI)
  86. reqRes := s.ctrl.reqRes
  87. if isAllowed(authReq.RequestURI) {
  88. reqRes = authorization.Response{Allow: true}
  89. }
  90. if reqRes.Err != "" {
  91. w.WriteHeader(http.StatusInternalServerError)
  92. }
  93. b, err := json.Marshal(reqRes)
  94. c.Assert(err, check.IsNil)
  95. s.ctrl.reqUser = authReq.User
  96. w.Write(b)
  97. })
  98. mux.HandleFunc("/AuthZPlugin.AuthZRes", func(w http.ResponseWriter, r *http.Request) {
  99. defer r.Body.Close()
  100. body, err := ioutil.ReadAll(r.Body)
  101. c.Assert(err, check.IsNil)
  102. authReq := authorization.Request{}
  103. err = json.Unmarshal(body, &authReq)
  104. c.Assert(err, check.IsNil)
  105. assertBody(c, authReq.RequestURI, authReq.ResponseHeaders, authReq.ResponseBody)
  106. assertAuthHeaders(c, authReq.ResponseHeaders)
  107. // Count only container list api
  108. if strings.HasSuffix(authReq.RequestURI, containerListAPI) {
  109. s.ctrl.psResponseCnt++
  110. }
  111. resRes := s.ctrl.resRes
  112. if isAllowed(authReq.RequestURI) {
  113. resRes = authorization.Response{Allow: true}
  114. }
  115. if resRes.Err != "" {
  116. w.WriteHeader(http.StatusInternalServerError)
  117. }
  118. b, err := json.Marshal(resRes)
  119. c.Assert(err, check.IsNil)
  120. s.ctrl.resUser = authReq.User
  121. w.Write(b)
  122. })
  123. err := os.MkdirAll("/etc/docker/plugins", 0755)
  124. c.Assert(err, checker.IsNil)
  125. fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", testAuthZPlugin)
  126. err = ioutil.WriteFile(fileName, []byte(s.server.URL), 0644)
  127. c.Assert(err, checker.IsNil)
  128. }
  129. // check for always allowed endpoints to not inhibit test framework functions
  130. func isAllowed(reqURI string) bool {
  131. for _, endpoint := range alwaysAllowed {
  132. if strings.HasSuffix(reqURI, endpoint) {
  133. return true
  134. }
  135. }
  136. return false
  137. }
  138. // assertAuthHeaders validates authentication headers are removed
  139. func assertAuthHeaders(c *check.C, headers map[string]string) error {
  140. for k := range headers {
  141. if strings.Contains(strings.ToLower(k), "auth") || strings.Contains(strings.ToLower(k), "x-registry") {
  142. c.Errorf("Found authentication headers in request '%v'", headers)
  143. }
  144. }
  145. return nil
  146. }
  147. // assertBody asserts that body is removed for non text/json requests
  148. func assertBody(c *check.C, requestURI string, headers map[string]string, body []byte) {
  149. if strings.Contains(strings.ToLower(requestURI), "auth") && len(body) > 0 {
  150. //return fmt.Errorf("Body included for authentication endpoint %s", string(body))
  151. c.Errorf("Body included for authentication endpoint %s", string(body))
  152. }
  153. for k, v := range headers {
  154. if strings.EqualFold(k, "Content-Type") && strings.HasPrefix(v, "text/") || v == "application/json" {
  155. return
  156. }
  157. }
  158. if len(body) > 0 {
  159. c.Errorf("Body included while it should not (Headers: '%v')", headers)
  160. }
  161. }
  162. func (s *DockerAuthzSuite) TearDownSuite(c *check.C) {
  163. if s.server == nil {
  164. return
  165. }
  166. s.server.Close()
  167. err := os.RemoveAll("/etc/docker/plugins")
  168. c.Assert(err, checker.IsNil)
  169. }
  170. func (s *DockerAuthzSuite) TestAuthZPluginAllowRequest(c *check.C) {
  171. // start the daemon and load busybox, --net=none build fails otherwise
  172. // cause it needs to pull busybox
  173. c.Assert(s.d.Start("--authorization-plugin="+testAuthZPlugin), check.IsNil)
  174. s.ctrl.reqRes.Allow = true
  175. s.ctrl.resRes.Allow = true
  176. c.Assert(s.d.LoadBusybox(), check.IsNil)
  177. // Ensure command successful
  178. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  179. c.Assert(err, check.IsNil)
  180. id := strings.TrimSpace(out)
  181. assertURIRecorded(c, s.ctrl.requestsURIs, "/containers/create")
  182. assertURIRecorded(c, s.ctrl.requestsURIs, fmt.Sprintf("/containers/%s/start", id))
  183. out, err = s.d.Cmd("ps")
  184. c.Assert(err, check.IsNil)
  185. c.Assert(assertContainerList(out, []string{id}), check.Equals, true)
  186. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  187. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  188. }
  189. func (s *DockerAuthzSuite) TestAuthZPluginTls(c *check.C) {
  190. const testDaemonHTTPSAddr = "tcp://localhost:4271"
  191. // start the daemon and load busybox, --net=none build fails otherwise
  192. // cause it needs to pull busybox
  193. if err := s.d.Start(
  194. "--authorization-plugin="+testAuthZPlugin,
  195. "--tlsverify",
  196. "--tlscacert",
  197. "fixtures/https/ca.pem",
  198. "--tlscert",
  199. "fixtures/https/server-cert.pem",
  200. "--tlskey",
  201. "fixtures/https/server-key.pem",
  202. "-H", testDaemonHTTPSAddr); err != nil {
  203. c.Fatalf("Could not start daemon with busybox: %v", err)
  204. }
  205. s.ctrl.reqRes.Allow = true
  206. s.ctrl.resRes.Allow = true
  207. out, _ := dockerCmd(
  208. c,
  209. "--tlsverify",
  210. "--tlscacert", "fixtures/https/ca.pem",
  211. "--tlscert", "fixtures/https/client-cert.pem",
  212. "--tlskey", "fixtures/https/client-key.pem",
  213. "-H",
  214. testDaemonHTTPSAddr,
  215. "version",
  216. )
  217. if !strings.Contains(out, "Server") {
  218. c.Fatalf("docker version should return information of server side")
  219. }
  220. c.Assert(s.ctrl.reqUser, check.Equals, "client")
  221. c.Assert(s.ctrl.resUser, check.Equals, "client")
  222. }
  223. func (s *DockerAuthzSuite) TestAuthZPluginDenyRequest(c *check.C) {
  224. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  225. c.Assert(err, check.IsNil)
  226. s.ctrl.reqRes.Allow = false
  227. s.ctrl.reqRes.Msg = unauthorizedMessage
  228. // Ensure command is blocked
  229. res, err := s.d.Cmd("ps")
  230. c.Assert(err, check.NotNil)
  231. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  232. c.Assert(s.ctrl.psResponseCnt, check.Equals, 0)
  233. // Ensure unauthorized message appears in response
  234. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: authorization denied by plugin %s: %s\n", testAuthZPlugin, unauthorizedMessage))
  235. }
  236. // TestAuthZPluginApiDenyResponse validates that when authorization plugin deny the request, the status code is forbidden
  237. func (s *DockerAuthzSuite) TestAuthZPluginApiDenyResponse(c *check.C) {
  238. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  239. c.Assert(err, check.IsNil)
  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. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  255. c.Assert(err, check.IsNil)
  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. c.Assert(s.d.Start("--authorization-plugin="+testAuthZPlugin), check.IsNil)
  272. s.ctrl.reqRes.Allow = true
  273. s.ctrl.resRes.Allow = true
  274. c.Assert(s.d.LoadBusybox(), check.IsNil)
  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. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  321. c.Assert(err, check.IsNil)
  322. s.ctrl.reqRes.Allow = true
  323. s.ctrl.resRes.Err = errorMessage
  324. // Ensure command is blocked
  325. res, err := s.d.Cmd("ps")
  326. c.Assert(err, check.NotNil)
  327. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s\n", testAuthZPlugin, authorization.AuthZApiResponse, errorMessage))
  328. }
  329. func (s *DockerAuthzSuite) TestAuthZPluginErrorRequest(c *check.C) {
  330. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  331. c.Assert(err, check.IsNil)
  332. s.ctrl.reqRes.Err = errorMessage
  333. // Ensure command is blocked
  334. res, err := s.d.Cmd("ps")
  335. c.Assert(err, check.NotNil)
  336. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s\n", testAuthZPlugin, authorization.AuthZApiRequest, errorMessage))
  337. }
  338. func (s *DockerAuthzSuite) TestAuthZPluginEnsureNoDuplicatePluginRegistration(c *check.C) {
  339. c.Assert(s.d.Start("--authorization-plugin="+testAuthZPlugin, "--authorization-plugin="+testAuthZPlugin), check.IsNil)
  340. s.ctrl.reqRes.Allow = true
  341. s.ctrl.resRes.Allow = true
  342. out, err := s.d.Cmd("ps")
  343. c.Assert(err, check.IsNil, check.Commentf(out))
  344. // assert plugin is only called once..
  345. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  346. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  347. }
  348. func (s *DockerAuthzSuite) TestAuthZPluginEnsureLoadImportWorking(c *check.C) {
  349. c.Assert(s.d.Start("--authorization-plugin="+testAuthZPlugin, "--authorization-plugin="+testAuthZPlugin), check.IsNil)
  350. s.ctrl.reqRes.Allow = true
  351. s.ctrl.resRes.Allow = true
  352. c.Assert(s.d.LoadBusybox(), check.IsNil)
  353. tmp, err := ioutil.TempDir("", "test-authz-load-import")
  354. c.Assert(err, check.IsNil)
  355. defer os.RemoveAll(tmp)
  356. savedImagePath := filepath.Join(tmp, "save.tar")
  357. out, err := s.d.Cmd("save", "-o", savedImagePath, "busybox")
  358. c.Assert(err, check.IsNil, check.Commentf(out))
  359. out, err = s.d.Cmd("load", "--input", savedImagePath)
  360. c.Assert(err, check.IsNil, check.Commentf(out))
  361. exportedImagePath := filepath.Join(tmp, "export.tar")
  362. out, err = s.d.Cmd("run", "-d", "--name", "testexport", "busybox")
  363. c.Assert(err, check.IsNil, check.Commentf(out))
  364. out, err = s.d.Cmd("export", "-o", exportedImagePath, "testexport")
  365. c.Assert(err, check.IsNil, check.Commentf(out))
  366. out, err = s.d.Cmd("import", exportedImagePath)
  367. c.Assert(err, check.IsNil, check.Commentf(out))
  368. }
  369. // assertURIRecorded verifies that the given URI was sent and recorded in the authz plugin
  370. func assertURIRecorded(c *check.C, uris []string, uri string) {
  371. var found bool
  372. for _, u := range uris {
  373. if strings.Contains(u, uri) {
  374. found = true
  375. break
  376. }
  377. }
  378. if !found {
  379. c.Fatalf("Expected to find URI '%s', recorded uris '%s'", uri, strings.Join(uris, ","))
  380. }
  381. }