docker_cli_authz_unix_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  67. b, err := json.Marshal(plugins.Manifest{Implements: []string{authorization.AuthZApiImplements}})
  68. c.Assert(err, check.IsNil)
  69. w.Write(b)
  70. })
  71. mux.HandleFunc("/AuthZPlugin.AuthZReq", func(w http.ResponseWriter, r *http.Request) {
  72. defer r.Body.Close()
  73. body, err := ioutil.ReadAll(r.Body)
  74. c.Assert(err, check.IsNil)
  75. authReq := authorization.Request{}
  76. err = json.Unmarshal(body, &authReq)
  77. c.Assert(err, check.IsNil)
  78. assertBody(c, authReq.RequestURI, authReq.RequestHeaders, authReq.RequestBody)
  79. assertAuthHeaders(c, authReq.RequestHeaders)
  80. // Count only container list api
  81. if strings.HasSuffix(authReq.RequestURI, containerListAPI) {
  82. s.ctrl.psRequestCnt++
  83. }
  84. s.ctrl.requestsURIs = append(s.ctrl.requestsURIs, authReq.RequestURI)
  85. reqRes := s.ctrl.reqRes
  86. if isAllowed(authReq.RequestURI) {
  87. reqRes = authorization.Response{Allow: true}
  88. }
  89. if reqRes.Err != "" {
  90. w.WriteHeader(http.StatusInternalServerError)
  91. }
  92. b, err := json.Marshal(reqRes)
  93. c.Assert(err, check.IsNil)
  94. s.ctrl.reqUser = authReq.User
  95. w.Write(b)
  96. })
  97. mux.HandleFunc("/AuthZPlugin.AuthZRes", func(w http.ResponseWriter, r *http.Request) {
  98. defer r.Body.Close()
  99. body, err := ioutil.ReadAll(r.Body)
  100. c.Assert(err, check.IsNil)
  101. authReq := authorization.Request{}
  102. err = json.Unmarshal(body, &authReq)
  103. c.Assert(err, check.IsNil)
  104. assertBody(c, authReq.RequestURI, authReq.ResponseHeaders, authReq.ResponseBody)
  105. assertAuthHeaders(c, authReq.ResponseHeaders)
  106. // Count only container list api
  107. if strings.HasSuffix(authReq.RequestURI, containerListAPI) {
  108. s.ctrl.psResponseCnt++
  109. }
  110. resRes := s.ctrl.resRes
  111. if isAllowed(authReq.RequestURI) {
  112. resRes = authorization.Response{Allow: true}
  113. }
  114. if resRes.Err != "" {
  115. w.WriteHeader(http.StatusInternalServerError)
  116. }
  117. b, err := json.Marshal(resRes)
  118. c.Assert(err, check.IsNil)
  119. s.ctrl.resUser = authReq.User
  120. w.Write(b)
  121. })
  122. err := os.MkdirAll("/etc/docker/plugins", 0755)
  123. c.Assert(err, checker.IsNil)
  124. fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", testAuthZPlugin)
  125. err = ioutil.WriteFile(fileName, []byte(s.server.URL), 0644)
  126. c.Assert(err, checker.IsNil)
  127. }
  128. // check for always allowed endpoints to not inhibit test framework functions
  129. func isAllowed(reqURI string) bool {
  130. for _, endpoint := range alwaysAllowed {
  131. if strings.HasSuffix(reqURI, endpoint) {
  132. return true
  133. }
  134. }
  135. return false
  136. }
  137. // assertAuthHeaders validates authentication headers are removed
  138. func assertAuthHeaders(c *check.C, headers map[string]string) error {
  139. for k := range headers {
  140. if strings.Contains(strings.ToLower(k), "auth") || strings.Contains(strings.ToLower(k), "x-registry") {
  141. c.Errorf("Found authentication headers in request '%v'", headers)
  142. }
  143. }
  144. return nil
  145. }
  146. // assertBody asserts that body is removed for non text/json requests
  147. func assertBody(c *check.C, requestURI string, headers map[string]string, body []byte) {
  148. if strings.Contains(strings.ToLower(requestURI), "auth") && len(body) > 0 {
  149. //return fmt.Errorf("Body included for authentication endpoint %s", string(body))
  150. c.Errorf("Body included for authentication endpoint %s", string(body))
  151. }
  152. for k, v := range headers {
  153. if strings.EqualFold(k, "Content-Type") && strings.HasPrefix(v, "text/") || v == "application/json" {
  154. return
  155. }
  156. }
  157. if len(body) > 0 {
  158. c.Errorf("Body included while it should not (Headers: '%v')", headers)
  159. }
  160. }
  161. func (s *DockerAuthzSuite) TearDownSuite(c *check.C) {
  162. if s.server == nil {
  163. return
  164. }
  165. s.server.Close()
  166. err := os.RemoveAll("/etc/docker/plugins")
  167. c.Assert(err, checker.IsNil)
  168. }
  169. func (s *DockerAuthzSuite) TestAuthZPluginAllowRequest(c *check.C) {
  170. // start the daemon and load busybox, --net=none build fails otherwise
  171. // cause it needs to pull busybox
  172. c.Assert(s.d.Start("--authorization-plugin="+testAuthZPlugin), check.IsNil)
  173. s.ctrl.reqRes.Allow = true
  174. s.ctrl.resRes.Allow = true
  175. c.Assert(s.d.LoadBusybox(), check.IsNil)
  176. // Ensure command successful
  177. out, err := s.d.Cmd("run", "-d", "busybox", "top")
  178. c.Assert(err, check.IsNil)
  179. id := strings.TrimSpace(out)
  180. assertURIRecorded(c, s.ctrl.requestsURIs, "/containers/create")
  181. assertURIRecorded(c, s.ctrl.requestsURIs, fmt.Sprintf("/containers/%s/start", id))
  182. out, err = s.d.Cmd("ps")
  183. c.Assert(err, check.IsNil)
  184. c.Assert(assertContainerList(out, []string{id}), check.Equals, true)
  185. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  186. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  187. }
  188. func (s *DockerAuthzSuite) TestAuthZPluginTls(c *check.C) {
  189. const testDaemonHTTPSAddr = "tcp://localhost:4271"
  190. // start the daemon and load busybox, --net=none build fails otherwise
  191. // cause it needs to pull busybox
  192. if err := s.d.Start(
  193. "--authorization-plugin="+testAuthZPlugin,
  194. "--tlsverify",
  195. "--tlscacert",
  196. "fixtures/https/ca.pem",
  197. "--tlscert",
  198. "fixtures/https/server-cert.pem",
  199. "--tlskey",
  200. "fixtures/https/server-key.pem",
  201. "-H", testDaemonHTTPSAddr); err != nil {
  202. c.Fatalf("Could not start daemon with busybox: %v", err)
  203. }
  204. s.ctrl.reqRes.Allow = true
  205. s.ctrl.resRes.Allow = true
  206. out, _ := dockerCmd(
  207. c,
  208. "--tlsverify",
  209. "--tlscacert", "fixtures/https/ca.pem",
  210. "--tlscert", "fixtures/https/client-cert.pem",
  211. "--tlskey", "fixtures/https/client-key.pem",
  212. "-H",
  213. testDaemonHTTPSAddr,
  214. "version",
  215. )
  216. if !strings.Contains(out, "Server") {
  217. c.Fatalf("docker version should return information of server side")
  218. }
  219. c.Assert(s.ctrl.reqUser, check.Equals, "client")
  220. c.Assert(s.ctrl.resUser, check.Equals, "client")
  221. }
  222. func (s *DockerAuthzSuite) TestAuthZPluginDenyRequest(c *check.C) {
  223. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  224. c.Assert(err, check.IsNil)
  225. s.ctrl.reqRes.Allow = false
  226. s.ctrl.reqRes.Msg = unauthorizedMessage
  227. // Ensure command is blocked
  228. res, err := s.d.Cmd("ps")
  229. c.Assert(err, check.NotNil)
  230. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  231. c.Assert(s.ctrl.psResponseCnt, check.Equals, 0)
  232. // Ensure unauthorized message appears in response
  233. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: authorization denied by plugin %s: %s\n", testAuthZPlugin, unauthorizedMessage))
  234. }
  235. // TestAuthZPluginApiDenyResponse validates that when authorization plugin deny the request, the status code is forbidden
  236. func (s *DockerAuthzSuite) TestAuthZPluginApiDenyResponse(c *check.C) {
  237. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  238. c.Assert(err, check.IsNil)
  239. s.ctrl.reqRes.Allow = false
  240. s.ctrl.resRes.Msg = unauthorizedMessage
  241. daemonURL, err := url.Parse(s.d.sock())
  242. conn, err := net.DialTimeout(daemonURL.Scheme, daemonURL.Path, time.Second*10)
  243. c.Assert(err, check.IsNil)
  244. client := httputil.NewClientConn(conn, nil)
  245. req, err := http.NewRequest("GET", "/version", nil)
  246. c.Assert(err, check.IsNil)
  247. resp, err := client.Do(req)
  248. c.Assert(err, check.IsNil)
  249. c.Assert(resp.StatusCode, checker.Equals, http.StatusForbidden)
  250. c.Assert(err, checker.IsNil)
  251. }
  252. func (s *DockerAuthzSuite) TestAuthZPluginDenyResponse(c *check.C) {
  253. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  254. c.Assert(err, check.IsNil)
  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. c.Assert(s.d.Start("--authorization-plugin="+testAuthZPlugin), check.IsNil)
  271. s.ctrl.reqRes.Allow = true
  272. s.ctrl.resRes.Allow = true
  273. c.Assert(s.d.LoadBusybox(), check.IsNil)
  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. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  320. c.Assert(err, check.IsNil)
  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. err := s.d.Start("--authorization-plugin=" + testAuthZPlugin)
  330. c.Assert(err, check.IsNil)
  331. s.ctrl.reqRes.Err = errorMessage
  332. // Ensure command is blocked
  333. res, err := s.d.Cmd("ps")
  334. c.Assert(err, check.NotNil)
  335. c.Assert(res, check.Equals, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s\n", testAuthZPlugin, authorization.AuthZApiRequest, errorMessage))
  336. }
  337. func (s *DockerAuthzSuite) TestAuthZPluginEnsureNoDuplicatePluginRegistration(c *check.C) {
  338. c.Assert(s.d.Start("--authorization-plugin="+testAuthZPlugin, "--authorization-plugin="+testAuthZPlugin), check.IsNil)
  339. s.ctrl.reqRes.Allow = true
  340. s.ctrl.resRes.Allow = true
  341. out, err := s.d.Cmd("ps")
  342. c.Assert(err, check.IsNil, check.Commentf(out))
  343. // assert plugin is only called once..
  344. c.Assert(s.ctrl.psRequestCnt, check.Equals, 1)
  345. c.Assert(s.ctrl.psResponseCnt, check.Equals, 1)
  346. }
  347. func (s *DockerAuthzSuite) TestAuthZPluginEnsureLoadImportWorking(c *check.C) {
  348. c.Assert(s.d.Start("--authorization-plugin="+testAuthZPlugin, "--authorization-plugin="+testAuthZPlugin), check.IsNil)
  349. s.ctrl.reqRes.Allow = true
  350. s.ctrl.resRes.Allow = true
  351. c.Assert(s.d.LoadBusybox(), check.IsNil)
  352. tmp, err := ioutil.TempDir("", "test-authz-load-import")
  353. c.Assert(err, check.IsNil)
  354. defer os.RemoveAll(tmp)
  355. savedImagePath := filepath.Join(tmp, "save.tar")
  356. out, err := s.d.Cmd("save", "-o", savedImagePath, "busybox")
  357. c.Assert(err, check.IsNil, check.Commentf(out))
  358. out, err = s.d.Cmd("load", "--input", savedImagePath)
  359. c.Assert(err, check.IsNil, check.Commentf(out))
  360. exportedImagePath := filepath.Join(tmp, "export.tar")
  361. out, err = s.d.Cmd("run", "-d", "--name", "testexport", "busybox")
  362. c.Assert(err, check.IsNil, check.Commentf(out))
  363. out, err = s.d.Cmd("export", "-o", exportedImagePath, "testexport")
  364. c.Assert(err, check.IsNil, check.Commentf(out))
  365. out, err = s.d.Cmd("import", exportedImagePath)
  366. c.Assert(err, check.IsNil, check.Commentf(out))
  367. }
  368. // assertURIRecorded verifies that the given URI was sent and recorded in the authz plugin
  369. func assertURIRecorded(c *check.C, uris []string, uri string) {
  370. var found bool
  371. for _, u := range uris {
  372. if strings.Contains(u, uri) {
  373. found = true
  374. break
  375. }
  376. }
  377. if !found {
  378. c.Fatalf("Expected to find URI '%s', recorded uris '%s'", uri, strings.Join(uris, ","))
  379. }
  380. }